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                = &resourceLBBackendServer{}
	_ resource.ResourceWithImportState = &resourceLBBackendServer{}
)

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

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

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

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

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

	tflog.Info(ctx, "Create resourceLBBackendServer: 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.LBBackendServerResource(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 *resourceLBBackendServer) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// Get current state
	var state models.ResourceLBBackendServerModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceLBBackendServer: Error get state")
		return
	}
	tflog.Info(ctx, "Read resourceLBBackendServer: 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 resourceLBBackendServer: Error set timeout")
		return
	}
	tflog.Info(ctx, "Read resourceLBBackendServer: 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.LBBackendServerResource(ctx, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceLBBackendServer: Error flatten")
		return
	}

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

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

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

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

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

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

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

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

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

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

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

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

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