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"
	decort "repository.basistech.ru/BASIS/decort-golang-sdk"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/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/cloudbroker/lb/flattens"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/lb/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/lb/schemas"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/lb/utilities"
)

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

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

// resourceLBFrontendBind is the resource implementation.
type resourceLBFrontendBind struct {
	client *decort.DecortClient
}

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

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

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

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

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

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

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

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

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

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

	// Delete existing flipgroup
	delReq := lb.FrontendBindDeleteRequest{
		LBID:         uint64(state.LBID.ValueInt64()),
		FrontendName: state.Frontend.ValueString(),
		BindingName:  state.Name.ValueString(),
	}

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

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

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

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

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

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