package cbVFpool

import (
	"context"
	"fmt"
	"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/vfpool"
	"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/vfpool/flattens"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/vfpool/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/vfpool/schemas"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/vfpool/utilities"
)

// Ensure the implementation satisfies the expected interfaces.
var (
	_ resource.Resource                = &resourceVFPool{}
	_ resource.ResourceWithImportState = &resourceVFPool{}
)

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

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

// Create creates the resource and sets the initial Terraform state.
func (r *resourceVFPool) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	// Get plan to create resource group
	var plan models.ResourceItemVFPoolModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceVFPool: Error receiving the plan")
		return
	}

	contextCreateMap := map[string]any{
		"name": plan.Name.ValueString(),
	}
	tflog.Info(ctx, "Create resourceVFPool: got plan successfully", contextCreateMap)
	tflog.Info(ctx, "Create resourceVFPool: start creating", contextCreateMap)

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

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

	// Make create request and get response
	id, diags := utilities.VFpoolResourceCreate(ctx, &plan, r.client)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}
	plan.ID = types.StringValue(strconv.Itoa(int(*id)))
	tflog.Info(ctx, "VFPoolResourceCreatee: VFPool created", map[string]any{"vfpool_id": id})

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

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.VFPoolResource(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
	}

}

// Read refreshes the Terraform state with the latest data.
func (r *resourceVFPool) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// Get current state
	var state models.ResourceItemVFPoolModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceVFPool: Error get state")
		return
	}
	tflog.Info(ctx, "Read resourceVFPool: got state successfully", map[string]any{"vfpool_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 resourceVFPool: Error set timeout")
		return
	}
	tflog.Info(ctx, "Read resourceVFPool: set timeouts successfully", map[string]any{
		"vfpool_id":   state.ID.ValueString(),
		"readTimeout": readTimeout})

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

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

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

// Update updates the resource and sets the updated Terraform state on success.
func (r *resourceVFPool) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
	// Retrieve values from plan
	var plan models.ResourceItemVFPoolModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceVFPool: Error receiving the plan")
		return
	}

	logMap := map[string]any{"vfpool_id": plan.ID.ValueString()}
	tflog.Info(ctx, "Update resourceVFPool: got plan successfully", logMap)

	// Retrieve values from state
	var state models.ResourceItemVFPoolModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceVFPool: Error receiving the state")
		return
	}
	tflog.Info(ctx, "Update resourceVFPool: got state successfully", logMap)

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

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

	_, err := strconv.Atoi(state.ID.ValueString())
	if err != nil {
		resp.Diagnostics.AddError("Update resourceVFPool: Cannot parse ID from state", err.Error())
		return
	}

	if !plan.Name.Equal(state.Name) || !plan.Description.Equal(state.Description) || !plan.AccountAccess.Equal(state.AccountAccess) || !plan.RGAccess.Equal(state.RGAccess) || !plan.Config.Equal(state.Config) {
		resp.Diagnostics.Append(utilities.UpdateVFpool(ctx, &state, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceVFPool: Error update VFPool")
			return
		}
	}

	if !plan.Enable.Equal(state.Enable) {
		resp.Diagnostics.Append(utilities.EnableDisableVFpool(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceVFPool: Error enabling/disabling VFPool")
			return
		}
	}

	tflog.Info(ctx, "Update resourceVFPool: VFPool update is completed", logMap)

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.VFPoolResource(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
	}
}

// Delete deletes the resource and removes the Terraform state on success.
func (r *resourceVFPool) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.ResourceItemVFPoolModel

	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceVFPool: Error get state")
		return
	}
	tflog.Info(ctx, "Delete resourceVFPool: got state successfully", map[string]any{"serice_id": state.ID.ValueString()})

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

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

	ID, err := strconv.Atoi(state.ID.ValueString())
	if err != nil {
		resp.Diagnostics.AddError("Delete resourceVFPool: Cannot parse ID from state", err.Error())
		return
	}

	if state.Status.ValueString() == "ENABLED" || state.Status.ValueString() == "CREATED" {
		reqDisable := vfpool.DisableRequest{
			VFPoolID: uint64(ID),
		}

		tflog.Info(ctx, fmt.Sprintf("resourceVFPool Delete: need to disable vfPool with ID: %d, after delete", ID))
		_, err = r.client.CloudBroker().VFPool().Disable(ctx, reqDisable)
		if err != nil {
			resp.Diagnostics.AddError("Delete resourceVFPool: Error disable VFPool with error: ", err.Error())
			return
		}
		tflog.Info(ctx, fmt.Sprintf("resourceVFPoolDelete: disable vfPool with ID: %d, complete", ID))
	}

	delReq := vfpool.DeleteRequest{
		VFPoolID: uint64(ID),
	}

	tflog.Info(ctx, "Delete resourceVFPool: before call cloudbroker().VFPool().Delete", map[string]any{"req": delReq})
	_, err = r.client.CloudBroker().VFPool().Delete(ctx, delReq)
	if err != nil {
		resp.Diagnostics.AddError("Delete resourceVFPool: Error deleting VFPool with error: ", err.Error())
		return
	}

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

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

// Metadata returns the resource type name.
func (r *resourceVFPool) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
	resp.TypeName = req.ProviderTypeName + "_cb_vfpool"
}

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

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