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

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

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

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

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

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

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

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

func (r *resourceLBFrontend) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) {
	tflog.Error(ctx, "Update resourceLBFrontend: This resource cannot be updated")
	resp.Diagnostics.AddError("This resource cannot be updated", "")
	return
}

func (r *resourceLBFrontend) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.ResourceLBFrontendModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceLBFrontend: Error get state")
		return
	}
	tflog.Info(ctx, "Delete resourceLBFrontend: 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 resourceLBFrontend: Error set timeout")
		return
	}
	tflog.Info(ctx, "Delete resourceLBFrontend: set timeouts successfully", map[string]any{
		"id":            state.ID.ValueString(),
		"deleteTimeout": readTimeout})

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

	// Delete existing lb frontend
	delReq := lb.FrontendDeleteRequest{
		LBID:         uint64(state.LBID.ValueInt64()),
		FrontendName: state.Name.ValueString(),
	}

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

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

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

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

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

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