package flipgroup

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

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

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

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

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

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

	plan.ID = types.StringValue(strconv.Itoa(int(flipgroupID)))
	//plan.CreatedBy = types.StringValue(time.Now().Format(time.RFC850))
	tflog.Info(ctx, "Create resourceFlipgroup: flipgroup created", map[string]any{"flipgroup_id": flipgroupID, "name": plan.Name.ValueString()})

	// Add computes after flipgroup creation, warnings added to resp.Diagnostics in case of failure
	if !plan.ClientIDs.IsUnknown() { // ClientIDs optional & computed
		resp.Diagnostics.Append(utilities.AddClientsFlipgroup(ctx, flipgroupID, &plan, r.client)...)
	}

	tflog.Info(ctx, "Create resourceFlipgroup: resource creation is completed", map[string]any{"flipgroup_id": flipgroupID})

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.FlipgroupResource(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 *resourceFlipgroup) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// Get current state
	var state models.ResourceFLIPGroupModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceFlipgroup: Error get state")
		return
	}
	tflog.Info(ctx, "Read resourceFlipgroup: got state successfully", map[string]any{"flipgroup_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 resourceFlipgroup: Error set timeout")
		return
	}
	tflog.Info(ctx, "Read resourceFlipgroup: set timeouts successfully", map[string]any{
		"flipgroup_id":  state.ID.ValueString(),
		"createTimeout": readTimeout})

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

	// Read status
	tflog.Info(ctx, "Read resourceFlipgroup: before FlipgroupReadStatus", map[string]any{"flipgroup_id": state.ID.ValueString()})
	resp.Diagnostics.Append(utilities.FlipgroupReadStatus(ctx, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceFlipgroup: Error reading status")
		return
	}

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

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

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

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

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

	// Checking for values in the platform
	tflog.Info(ctx, "Update resourceFlipgroup: starting input checks", map[string]any{"flipgroup_id": plan.ID.ValueString()})
	resp.Diagnostics.Append(resourceFlipgroupInputChecks(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceFlipgroup: Error input checks")
		return
	}
	tflog.Info(ctx, "Update resourceFlipgroup: input checks successful", map[string]any{"flipgroup_id": plan.ID.ValueString()})

	flipgroupId, err := strconv.ParseUint(state.ID.ValueString(), 10, 64)
	if err != nil {
		resp.Diagnostics.AddError(fmt.Sprintf("Cannot parse flipgroup ID %s from state", state.ID.ValueString()), err.Error())
		return
	}

	if !plan.Name.Equal(state.Name) || (!plan.Description.IsNull() && !plan.Description.Equal(state.Description)) {
		resp.Diagnostics.Append(utilities.EditFlipgroup(ctx, flipgroupId, &plan, &state, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceFlipgroup: Error editing flipgroup")
			return
		}
	}

	if !plan.ClientIDs.IsUnknown() && !plan.ClientIDs.Equal(state.ClientIDs) {
		resp.Diagnostics.Append(utilities.UpdateClientIDsFlipgroup(ctx, flipgroupId, &plan, &state, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceFlipgroup: Error editing client IDs")
			return
		}
	}

	tflog.Info(ctx, "Update resourceFlipgroup: resource update is completed", map[string]any{"flipgroup_id": plan.ID.ValueString()})

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

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

	// Delete existing flipgroup
	delReq := flipgroup.DeleteRequest{
		FLIPGroupID: uint64(state.FlipgroupID.ValueInt64()),
	}

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

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

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

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

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