package k8ci

import (
	"context"
	"reflect"
	"strconv"

	"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
	"github.com/hashicorp/terraform-plugin-framework/diag"
	"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/k8ci"
	"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/k8ci/flattens"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/k8ci/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/k8ci/schemas"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/k8ci/utilities"
)

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

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

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

// Create creates the resource and sets the initial Terraform state.
func (r *resourceK8CI) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	// Get plan to create resource group
	var plan models.ResourceK8CIModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceK8CI: Error receiving the plan")
		return
	}
	tflog.Info(ctx, "Create resourceK8CI: got plan successfully", map[string]any{"name": plan.Name.ValueString()})
	tflog.Info(ctx, "Create resourceK8CI: start creating", map[string]any{"name": plan.Name.ValueString()})

	// Set timeouts
	createTimeout, diags := plan.Timeouts.Create(ctx, constants.Timeout600s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceK8CI: Error set timeout")
		return
	}
	tflog.Info(ctx, "Create resourceK8CI: 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 resourceK8CI: starting input checks", map[string]any{"name": plan.Name.ValueString()})
	resp.Diagnostics.Append(resourceK8CIInputChecks(ctx, &plan, r.client)...)
	if diags.HasError() {
		tflog.Error(ctx, "Create resourceK8CI: Error input checks")
		return
	}
	tflog.Info(ctx, "Create resourceK8CI: input checks successful", map[string]any{"name": plan.Name.ValueString()})

	// Make create request and get response
	createReq, diags := utilities.CreateRequestResourceK8CI(ctx, &plan)
	resp.Diagnostics.Append(diags...)
	if diags.HasError() {
		tflog.Error(ctx, "Create resourceK8CI: Error response for create request of resource k8ci")
		return
	}

	tflog.Info(ctx, "Create resourceK8CI: before call CloudBroker().K8CI().Create", map[string]any{"req": createReq})
	k8ciid, err := r.client.CloudBroker().K8CI().Create(ctx, createReq)
	if err != nil {
		resp.Diagnostics.AddError(
			"Create resourceK8CI: unable to Create k8ci",
			err.Error(),
		)
		return
	}
	plan.Id = types.StringValue(strconv.Itoa(int(k8ciid)))
	tflog.Info(ctx, "Create resourceK8CI: k8ci created", map[string]any{"k8ci_id": k8ciid, "name": plan.Name.ValueString()})

	// additional settings after k8ci creation: in case of failures, warnings are added to resp.Diagnostics,
	// because additional settings failure is not critical. If errors were added instead of warnings, terraform
	// framework would mark resource as tainted and delete it, which would be unwanted behaviour.

	// enable/disable of k8ci after creation, warnings added to resp.Diagnostics in case of failure.
	temp := utilities.K8CIResourceEnableDisable(ctx, &plan, r.client)
	for _, d := range temp {
		if d.Severity() == diag.SeverityError {
			resp.Diagnostics.AddWarning(d.Summary(), d.Detail())
		}
	}

	tflog.Info(ctx, "Create resourceK8CI: resource creation is completed", map[string]any{"k8ci_id": k8ciid})

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

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

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

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

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

// Update updates the resource and sets the updated Terraform state on success.
func (r *resourceK8CI) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
	// Retrieve values from plan
	var plan models.ResourceK8CIModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceK8CI: Error receiving the plan")
		return
	}
	tflog.Info(ctx, "Update resourceK8CI: got plan successfully", map[string]any{"k8ci_id": plan.Id.ValueString()})

	// Retrieve values from state
	var state models.ResourceK8CIModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceK8CI: Error receiving the state")
		return
	}
	tflog.Info(ctx, "Update resourceK8CI: got state successfully", map[string]any{"k8ci_id": state.Id.ValueString()})

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

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

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

	// Checking that immutable variables have not changed
	tflog.Info(ctx, "Update resourceK8CI: starting immutable variables checks", map[string]any{"k8ci_id": plan.Id.ValueString()})
	resp.Diagnostics.Append(utilities.K8CIIUpdateVarChecks(&plan, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceK8CI: Error input checks")
		return
	}
	tflog.Info(ctx, "Update resourceK8CI: input checks successful", map[string]any{"k8ci_id": state.Id.ValueString()})

	plan.Id = state.Id

	// grant/revoke access for K8CI
	if !reflect.DeepEqual(plan.SharedWith, state.SharedWith) {
		resp.Diagnostics.Append(utilities.K8CISharedWithUpdate(ctx, &plan, &state, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceK8CI: Error grant/revoke access for k8ci")
			return
		}
	}

	// enable or disable k8ci
	if !plan.Enabled.Equal(state.Enabled) {
		resp.Diagnostics.Append(utilities.K8CIResourceEnableDisable(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceK8CI: Error enable/disable k8ci")
			return
		}
	}

	tflog.Info(ctx, "Update resourceK8CI: resource update is completed", map[string]any{"k8ci_id": plan.Id.ValueString()})

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

	// Set state to fully populated data
	diags = resp.State.Set(ctx, plan)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}
}

// Delete deletes the resource and removes the Terraform state on success.
func (r *resourceK8CI) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.ResourceK8CIModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceK8CI: Error get state")
		return
	}
	tflog.Info(ctx, "Delete resourceK8CI: got state successfully", map[string]any{"k8ci_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 resourceK8CI: Error set timeout")
		return
	}
	tflog.Info(ctx, "Delete resourceK8CI: set timeouts successfully", map[string]any{
		"k8ci_id":       state.Id.ValueString(),
		"deleteTimeout": deleteTimeout})

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

	k8ciid, err := strconv.ParseUint(state.Id.ValueString(), 10, 64)
	if err != nil {
		diags.AddError("Cannot parsed ID K8CI from state", err.Error())
		return
	}

	// Delete existing resource group
	delReq := k8ci.DeleteRequest{
		K8CIID:      k8ciid,
		Permanently: state.Permanently.ValueBool(),
	}

	_, err = r.client.CloudBroker().K8CI().Delete(ctx, delReq)
	if err != nil {
		resp.Diagnostics.AddError("Delete resourceK8CI: Error deleting k8ci with error: ", err.Error())
		return
	}

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

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

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

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