package lb

import (
	"context"
	"strconv"

	"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
	"github.com/hashicorp/terraform-plugin-framework/diag"
	"github.com/hashicorp/terraform-plugin-framework/path"
	"github.com/hashicorp/terraform-plugin-framework/resource"
	"github.com/hashicorp/terraform-plugin-framework/resource/schema"
	"github.com/hashicorp/terraform-plugin-framework/types"
	"github.com/hashicorp/terraform-plugin-log/tflog"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/lb/flattens"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/lb/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/lb/schemas"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/lb/utilities"
)

var (
	_ resource.Resource                = &resourceLB{}
	_ resource.ResourceWithImportState = &resourceLB{}
)

// NewResourceLB is a helper function to simplify the provider implementation.
func NewResourceLB() resource.Resource {
	return &resourceLB{}
}

// resourceLB is the resource implementation.
type resourceLB struct {
	client *client.Client
}

func (r *resourceLB) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	// Get plan to create lb
	var plan models.ResourceLBModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceLB: Error receiving the plan")
		return
	}
	tflog.Info(ctx, "Create resourceLB: start creating", map[string]any{"name": plan.Name.ValueString()})

	// Set timeouts
	createTimeout, diags := plan.Timeouts.Create(ctx, constants.Timeout300s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceLB: Error set timeout")
		return
	}
	tflog.Info(ctx, "Create resourceLB: set timeouts successfully", map[string]any{
		"name":          plan.Name.ValueString(),
		"createTimeout": createTimeout})

	ctx, cancel := context.WithTimeout(ctx, createTimeout)
	defer cancel()

	// Check if input values are valid in the platform
	tflog.Info(ctx, "Create resourceLB: starting input checks", map[string]any{"name": plan.Name.ValueString()})
	resp.Diagnostics.Append(resourceLBInputChecks(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceLB: Error input checks")
		return
	}
	tflog.Info(ctx, "Create resourceLB: input checks successful", map[string]any{"name": plan.Name.ValueString()})

	// Make create request and get response for creation
	lbId, diags := utilities.CreateResourceLB(ctx, &plan, r.client)
	if diags.HasError() {
		resp.Diagnostics.Append(diags...)
		tflog.Error(ctx, "Create resourceLB: Error response for create resource LB")
		return
	}
	plan.ID = types.StringValue(strconv.Itoa(int(lbId)))

	// additional settings after lb creation: in case of failures, warnings are added to resp.Diagnostics,
	// because additional settings failure is not critical. If errors were added instead of warnings, terraform
	// framework would mark resource as tainted and delete it, which would be unwanted behaviour.

	// enable or disable lb, warnings added to resp.Diagnostics in case of failure.
	if !plan.Enable.ValueBool() { // Enable is optional
		diags := utilities.LBEnableDisable(ctx, &plan, r.client)
		for _, d := range diags {
			if d.Severity() == diag.SeverityError {
				resp.Diagnostics.AddWarning(d.Summary(), d.Detail())
			}
		}
	}

	tflog.Info(ctx, "Create resourceLB: resource creation is completed", map[string]any{"id": lbId})

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.LBResource(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		return
	}

	// Set state to fully populated data
	resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
	if resp.Diagnostics.HasError() {
		return
	}
}

func (r *resourceLB) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// Get current state
	var state models.ResourceLBModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceLB: Error get state")
		return
	}
	tflog.Info(ctx, "Read resourceLB: got state successfully", map[string]any{"ID": state.ID.ValueString()})

	// Set timeouts
	readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout300s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceLB: Error set timeout")
		return
	}
	tflog.Info(ctx, "Read resourceLB: set timeouts successfully", map[string]any{
		"ID":          state.ID.ValueString(),
		"readTimeout": readTimeout})

	ctx, cancel := context.WithTimeout(ctx, readTimeout)
	defer cancel()

	// Read status lb and if it is necessary to restore it
	resp.Diagnostics.Append(utilities.LBReadStatus(ctx, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error read status or restore")
		return
	}

	// Overwrite items with refreshed state
	resp.Diagnostics.Append(flattens.LBResource(ctx, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceLB: Error flatten")
		return
	}

	// Set refreshed state
	resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceLB: Error set state")
		return
	}
	tflog.Info(ctx, "End read resourceLB")
}

func (r *resourceLB) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
	// Retrieve values from plan
	var plan models.ResourceLBModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceLB: Error receiving the plan")
		return
	}
	tflog.Info(ctx, "Update resourceLB: got plan successfully", map[string]any{"ID": plan.ID.ValueString()})

	// Retrieve values from state
	var state models.ResourceLBModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceLB: Error receiving the state")
		return
	}
	tflog.Info(ctx, "Update resourceLB: got state successfully", map[string]any{"ID": plan.ID.ValueString()})

	// Set timeouts
	updateTimeout, diags := plan.Timeouts.Update(ctx, constants.Timeout300s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error set timeout")
		return
	}
	tflog.Info(ctx, "Update resourceLB: set timeouts successfully", map[string]any{
		"ID":            state.ID.ValueString(),
		"updateTimeout": updateTimeout})

	ctx, cancel := context.WithTimeout(ctx, updateTimeout)
	defer cancel()

	// Checking for values in the platform
	tflog.Info(ctx, "Update resourceLB: starting input checks", map[string]any{"ID": plan.ID.ValueString()})
	resp.Diagnostics.Append(resourceLBInputChecks(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceLB: Error input checks")
		return
	}
	tflog.Info(ctx, "Update resourceLB: input checks successful", map[string]any{"ID": plan.ID.ValueString()})

	// Read status lb and if it is necessary to restore it
	resp.Diagnostics.Append(utilities.LBReadStatus(ctx, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error read status or restore")
		return
	}

	// Update ha mode lb
	if !plan.HAMode.Equal(state.HAMode) && plan.HAMode.ValueBool() {
		resp.Diagnostics.Append(utilities.LBUpdateHaMode(ctx, &state, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceLB: Error update ha mode")
			return
		}
	}

	// Update sysctl LB params
	if !plan.SysctlParams.Equal(state.SysctlParams) {
		resp.Diagnostics.Append(utilities.LBUpdateSysctlParams(ctx, &plan, &state, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceLB: Error update sysctl LB params")
			return
		}
	}

	plan.ID = types.StringValue(strconv.Itoa(int(state.LBID.ValueInt64())))

	// Enable/disable LB
	if !plan.Enable.Equal(state.Enable) {
		resp.Diagnostics.Append(utilities.LBEnableDisable(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceLB: Error enable/disable LB")
			return
		}
	}

	// Start/stop LB
	if !plan.Start.Equal(state.Start) {
		resp.Diagnostics.Append(utilities.LBStartStop(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceLB: Error start/stop LB")
			return
		}
	}

	// Update description LB
	if !plan.Description.IsUnknown() && !plan.Description.Equal(state.Description) {
		resp.Diagnostics.Append(utilities.LBUpdateDescription(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceLB: Error update LB description")
			return
		}
	}

	// Restart LB
	if !plan.Restart.Equal(state.Restart) && plan.Restart.ValueBool() {
		resp.Diagnostics.Append(utilities.LBRestart(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceLB: Error update LB description")
			return
		}
	}

	// Config reset
	if !plan.ConfigReset.Equal(state.Restart) && plan.ConfigReset.ValueBool() {
		resp.Diagnostics.Append(utilities.LBConfigReset(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceLB: Error update LB description")
			return
		}
	}

	tflog.Info(ctx, "Update resourceLB: resource update is completed", map[string]any{"ID": plan.ID.ValueString()})

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.LBResource(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		return
	}

	// Set state to fully populated data
	resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
	if resp.Diagnostics.HasError() {
		return
	}
}

func (r *resourceLB) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.ResourceLBModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceLB: Error get state")
		return
	}
	tflog.Info(ctx, "Delete resourceLB: got state successfully", map[string]any{"ID": state.ID.ValueString()})

	// Set timeouts
	readTimeout, diags := state.Timeouts.Delete(ctx, constants.Timeout300s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceLB: Error set timeout")
		return
	}
	tflog.Info(ctx, "Delete resourceLB: set timeouts successfully", map[string]any{
		"id":            state.ID.ValueString(),
		"deleteTimeout": readTimeout})

	ctx, cancel := context.WithTimeout(ctx, readTimeout)
	defer cancel()

	// Delete existing lb
	delReq := lb.DeleteRequest{
		LBID:        uint64(state.LBID.ValueInt64()),
		Permanently: state.Permanently.ValueBool(),
	}

	tflog.Info(ctx, "Delete resourceLB: calling CloudAPI().LB().Delete", map[string]any{
		"ID":  state.ID.ValueString(),
		"req": delReq,
	})
	_, err := r.client.CloudAPI().LB().Delete(ctx, delReq)
	if err != nil {
		resp.Diagnostics.AddError("Delete resourceLB: Error deleting", err.Error())
		return
	}

	tflog.Info(ctx, "End delete resource lb ", map[string]any{"id": state.ID.ValueString()})
}

func (r *resourceLB) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
	resp.Schema = schema.Schema{
		Attributes: schemas.MakeSchemaResourceLB(),
		Blocks: map[string]schema.Block{
			"timeouts": timeouts.Block(ctx, timeouts.Opts{Create: true, Read: true, Update: true, Delete: true}),
		},
	}
}

func (r *resourceLB) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
	resp.TypeName = req.ProviderTypeName + "_lb"
}

// Configure adds the provider configured client to the resource.
func (r *resourceLB) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
	tflog.Info(ctx, "Get Configure resourceLB")
	r.client = client.Resource(ctx, &req, resp)
	tflog.Info(ctx, "Getting Configure resourceLB successfully")
}

func (r *resourceLB) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
	// Retrieve import ID and save to id attribute
	resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
