package lb

import (
	"context"
	"strconv"

	"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
	"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                = &resourceLBBackend{}
	_ resource.ResourceWithImportState = &resourceLBBackend{}
)

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

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

func (r *resourceLBBackend) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	// Get plan to create lb backend
	var plan models.ResourceLBBackendModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceLBBackend: Error receiving the plan")
		return
	}
	tflog.Info(ctx, "Create resourceLBBackend: 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 resourceLBBackend: Error set timeout")
		return
	}
	tflog.Info(ctx, "Create resourceLBBackend: 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 resourceLBBackend: starting input checks", map[string]any{"name": plan.Name.ValueString()})
	resp.Diagnostics.Append(resourceLBBackendInputChecks(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceLBBackend: Error input checks")
		return
	}
	tflog.Info(ctx, "Create resourceLBBackend: input checks successful", map[string]any{"name": plan.Name.ValueString()})

	// Make create request and get response for creation
	diags = utilities.CreateResourceLBBackend(ctx, &plan, r.client)
	if diags.HasError() {
		resp.Diagnostics.Append(diags...)
		tflog.Error(ctx, "Create resourceLBBackend: Error response for create resource LBBackend")
		return
	}

	plan.ID = types.StringValue(strconv.Itoa(int(plan.LBID.ValueInt64())) + "#" + plan.Name.ValueString())

	tflog.Info(ctx, "Create resourceLBBackend: resource creation is completed", map[string]any{"name": plan.Name.ValueString()})

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.LBBackendResource(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 *resourceLBBackend) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// Get current state
	var state models.ResourceLBBackendModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceLBBackend: Error get state")
		return
	}
	tflog.Info(ctx, "Read resourceLBBackend: 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 resourceLBBackend: Error set timeout")
		return
	}
	tflog.Info(ctx, "Read resourceLBBackend: set timeouts successfully", map[string]any{
		"ID":          state.ID.ValueString(),
		"readTimeout": readTimeout})

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

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

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

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

	// Retrieve values from state
	var state models.ResourceLBBackendModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceLBBackend: Error receiving the state")
		return
	}
	tflog.Info(ctx, "Update resourceLBBackend: 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 resourceLBBackend: 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 resourceLBBackend: starting input checks", map[string]any{"ID": plan.ID.ValueString()})
	resp.Diagnostics.Append(resourceLBBackendInputChecks(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceLBBackend: Error input checks")
		return
	}
	tflog.Info(ctx, "Update resourceLBBackend: input checks successful", map[string]any{"ID": plan.ID.ValueString()})

	// Check and update resource
	resp.Diagnostics.Append(utilities.UpdateLBBackend(ctx, &plan, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceLBBackend: Error editing lb backend")
		return
	}

	plan.ID = types.StringValue(strconv.Itoa(int(plan.LBID.ValueInt64())) + "#" + plan.Name.ValueString())
	tflog.Info(ctx, "Update resourceLBBackend: 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.LBBackendResource(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 *resourceLBBackend) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.ResourceLBBackendModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceLBBackend: Error get state")
		return
	}
	tflog.Info(ctx, "Delete resourceLBBackend: 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 resourceLBBackend: Error set timeout")
		return
	}
	tflog.Info(ctx, "Delete resourceLBBackend: set timeouts successfully", map[string]any{
		"id":            state.ID.ValueString(),
		"deleteTimeout": readTimeout})

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

	// Delete existing lb backend
	delReq := lb.BackendDeleteRequest{
		LBID:        uint64(state.LBID.ValueInt64()),
		BackendName: state.Name.ValueString(),
	}

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

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

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

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

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

func (r *resourceLBBackend) 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)
}
