package cbAccount

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

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

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

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

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

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

	diags, id := utilities.UtilityAccountCreate(ctx, &plan, r.client)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceAccount: error with UtilityAccountCreate")
		return
	}

	plan.Id = types.StringValue(strconv.Itoa(int(*id)))

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.AccountResource(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		return
	}

	tflog.Info(ctx, "resourceAccount: Account created", map[string]any{"account_id": id})

	resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
	if resp.Diagnostics.HasError() {
		return
	}
}

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

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

	// read status
	resp.Diagnostics.Append(utilities.AccountReadStatus(ctx, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceAccount: Error reading status")
		return
	}

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

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

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

	logMap := map[string]any{"account_id": plan.Id.ValueString()}
	tflog.Info(ctx, "Update resourceAccount: got plan successfully", logMap)

	// Retrieve values from state
	var state models.ResourceAccountModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceAccount: Error receiving the state")
		return
	}
	tflog.Info(ctx, "Update resourceAccount: 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 resourceAccount: Error set timeout")
		return
	}
	tflog.Info(ctx, "Update resourceAccount: set timeouts successfully", map[string]any{
		"account_id":    state.Id.ValueString(),
		"updateTimeout": updateTimeout})

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

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

	// enable/disable account
	if !plan.Enable.Equal(state.Enable) && !plan.Enable.IsNull() {
		resp.Diagnostics.Append(utilities.EnableDisableAccount(ctx, uint64(accountId), plan.Enable.ValueBool(), r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceAccount: Error enabling/disabling account")
			return
		}
	}

	// general update account
	resp.Diagnostics.Append(utilities.UpdateAccount(ctx, uint64(accountId), &plan, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceAccount: Error with general account update")
		return
	}

	// cpu_allocation_parameter
	if !plan.CPUAllocationParameter.Equal(state.CPUAllocationParameter) && !plan.CPUAllocationParameter.IsNull() && plan.CPUAllocationParameter.ValueString() != "" {
		resp.Diagnostics.Append(utilities.UtilityAccountCPUParameterUpdate(ctx, uint64(state.AccountID.ValueInt64()), &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceAccount: Error update CPUAllocationParameter ")
			return
		}
	}

	// cpu_allocation_ratio
	if !plan.CPUAllocationRatio.Equal(state.CPUAllocationRatio) && !plan.CPUAllocationRatio.IsNull() {
		resp.Diagnostics.Append(utilities.UtilityAccountCPURatioUpdate(ctx, uint64(accountId), &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceAccount: Error update CPUAllocationRatio ")
			return
		}
	}

	// add/delete users
	if !plan.Users.Equal(state.Users) {
		resp.Diagnostics.Append(utilities.AddDeleteUsersAccount(ctx, uint64(accountId), &plan, &state, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceAccount: Error adding/deleting users to/from account")
			return
		}
	}

	// available_templates
	if !plan.AvailableTemplates.Equal(state.AvailableTemplates) {
		resp.Diagnostics.Append(utilities.UtilityAccountAvailiableTemplatesUpdate(ctx, &state, &plan, false, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceAccount: Error update AvailiableTemplates")
			return
		}
	}

	// compute_features
	if !plan.ComputeFeatures.Equal(state.ComputeFeatures) {
		resp.Diagnostics.Append(utilities.UtilityAccountComputeFeaturesUpdate(ctx, uint64(accountId), &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceAccount: Error update ComputeFeatures")
			return
		}
	}

	tflog.Info(ctx, "Update resourceAccount: account update is completed", logMap)

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.AccountResource(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 *resourceAccount) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.ResourceAccountModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceAccount: Error get state")
		return
	}
	tflog.Info(ctx, "Delete resourceAccount: got state successfully", map[string]any{"account_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 resourceAccount: Error set timeout")
		return
	}
	tflog.Info(ctx, "Delete resourceAccount: set timeouts successfully", map[string]any{
		"account_id":    state.Id.ValueString(),
		"deleteTimeout": deleteTimeout})

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

	permanently := state.Permanently.ValueBool()
	if state.Permanently.IsNull() {
		permanently = true
	} // default true

	// Delete existing resource group
	delReq := account.DeleteRequest{
		AccountID:   uint64(state.AccountID.ValueInt64()),
		Permanently: permanently,
	}

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

	tflog.Info(ctx, "End delete resourceAccount", map[string]any{"account_id": state.Id.ValueString()})
}

// Schema defines the schema for the resource.
func (r *resourceAccount) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
	resp.Schema = schema.Schema{
		Attributes: schemas.MakeSchemaResourceAccount(),
		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 *resourceAccount) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
	resp.TypeName = req.ProviderTypeName + "_cb_account"
}

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

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