package rg

import (
	"context"
	"fmt"
	"reflect"
	"strconv"
	"time"

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

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

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

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

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

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

	tflog.Info(ctx, "Create resourceRG: before call CloudAPI().RG().Create", map[string]any{"req": createReq})
	rgId, err := r.client.CloudAPI().RG().Create(ctx, createReq)
	if err != nil {
		resp.Diagnostics.AddError(
			"Create resourceRG: unable to Create RG",
			err.Error(),
		)
		return
	}
	plan.Id = types.StringValue(strconv.Itoa(int(rgId)))
	tflog.Info(ctx, "Create resourceRG: resource group created", map[string]any{"rgId": rgId, "name": plan.Name.ValueString()})

	// additional settings after rg 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.

	// grant access to resource group if needed, warnings added to resp.Diagnostics in case of failure.
	resp.Diagnostics.Append(utilities.AccessCreateRG(ctx, rgId, &plan, r.client)...)

	// set def_net for resource group if needed, warnings added to resp.Diagnostics in case of failure.
	resp.Diagnostics.Append(utilities.SetDefNetCreateRG(ctx, rgId, &plan, r.client)...)

	// enable/disable of resource group after creation, warnings added to resp.Diagnostics in case of failure.
	resp.Diagnostics.Append(utilities.EnableDisableCreateRG(ctx, rgId, &plan, r.client)...)

	tflog.Info(ctx, "Create resourceRG: resource creation is completed", map[string]any{"rg_id": rgId})

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

	// Set data last update
	plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))

	// 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 *resourceRG) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// Get current state
	var state models.ResourceRGModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceRG: Error get state")
		return
	}
	tflog.Info(ctx, "Read resourceRG: got state successfully", map[string]any{"rg_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 resourceRG: Error set timeout")
		return
	}
	tflog.Info(ctx, "Read resourceRG: set timeouts successfully", map[string]any{
		"rg_id":       state.Id.ValueString(),
		"readTimeout": readTimeout})

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

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

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

	// Set refreshed state
	resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceRG: 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 *resourceRG) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
	// Retrieve values from plan
	var plan models.ResourceRGModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceRG: Error receiving the plan")
		return
	}
	tflog.Info(ctx, "Update resourceRG: got plan successfully", map[string]any{"rg_id": plan.Id.ValueString()})

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

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

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

	rgId, err := strconv.ParseUint(state.Id.ValueString(), 10, 64)
	if err != nil {
		diags.AddError("Cannot parse resource group ID from state", err.Error())
		return
	}

	// Get current resource group values
	recordRG, err := utilities.RGCheckPresence(ctx, rgId, r.client)
	if err != nil {
		resp.Diagnostics.AddError(
			"Update resourceRG: unable to Update RG after input checks",
			err.Error(),
		)
		return
	}

	tflog.Info(ctx, "Update resourceRG: check status for RG", map[string]any{"rg_id": recordRG.ID, "status": recordRG.Status})

	// Validate if changes in plan are allowed
	tflog.Info(ctx, "Update resourceRG: checking def_net is not empty in case of change", map[string]any{
		"rg_id": state.Id.ValueString()})

	tflog.Info(ctx, "Update resourceRG: checking def_net_type, ipcidr, ext_ip are not changed", map[string]any{
		"rg_id":              state.Id.ValueString(),
		"def_net_type_plan":  plan.DefNetType.ValueString(),
		"def_net_type_state": state.DefNetType.ValueString(),
		"ipcidr_plan":        plan.IPCIDR.ValueString(),
		"ipcidr_state":       state.IPCIDR.ValueString(),
		"ext_ip_plan":        plan.ExtIP.ValueString(),
		"ext_ip_state":       state.ExtIP.ValueString(),
	})

	if !plan.DefNetType.Equal(state.DefNetType) {
		resp.Diagnostics.AddWarning(
			"Update resourceRG: Invalid input provided. Warning can be ignored if resource was imported.",
			fmt.Sprintf("block def_net_type must not be changed for resource with rg_id %d", recordRG.ID),
		)
	}

	if !plan.IPCIDR.Equal(state.IPCIDR) {
		resp.Diagnostics.AddError(
			"Update resourceRG: Invalid input provided",
			fmt.Sprintf("block ipcidr must not be changed for resource with rg_id %d", recordRG.ID),
		)
		return
	}
	if !plan.ExtIP.Equal(state.ExtIP) {
		resp.Diagnostics.AddError(
			"Update resourceRG: Invalid input provided",
			fmt.Sprintf("block ext_ip must not be changed for resource with rg_id %d", recordRG.ID),
		)
		return
	}

	// update RG if any of the fields name, description, register_computes or quota has been changed
	resp.Diagnostics.Append(utilities.UpdateRG(ctx, rgId, &plan, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceRG: Error updating rg")
		return
	}

	// enable or disable RG
	if !plan.Enable.Equal(state.Enable) {
		resp.Diagnostics.Append(utilities.EnableDisableUpdateRG(ctx, rgId, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceRG: Error enable/disable rg")
			return
		}
	}

	// grant/revoke access for RG
	if !reflect.DeepEqual(plan.Access, state.Access) {
		resp.Diagnostics.Append(utilities.AccessUpdateRG(ctx, rgId, &plan, &state, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceRG: Error grant/revoke access for rg")
			return
		}
	}

	// set new def_net is needed
	if !reflect.DeepEqual(plan.DefNet, state.DefNet) {
		resp.Diagnostics.Append(utilities.SetDefNetUpdateRG(ctx, rgId, &plan, &state, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceRG: Unable to setDefNet for RG")
			return
		}
	}

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

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

	// Set data last update
	plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))

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

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

	// Delete existing resource group
	delReq := rg.DeleteRequest{
		RGID: uint64(state.RGID.ValueInt64()),
	}

	if state.Force.IsNull() {
		delReq.Force = true // default value
	} else {
		delReq.Force = state.Force.ValueBool()
	}
	if state.Permanently.IsNull() {
		delReq.Permanently = true // default value
	} else {
		delReq.Permanently = state.Permanently.ValueBool()
	}
	_, err := r.client.CloudAPI().RG().Delete(ctx, delReq)
	if err != nil {
		resp.Diagnostics.AddError("Delete resourceRG: Error deleting resource group with error: ", err.Error())
		return
	}

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

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

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

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