package disks

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

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

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

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

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

	ctxCreateSnpsht := map[string]any{
		"disk_id": plan.DiskID.ValueInt64(),
		"label":   plan.Label.ValueString(),
	}
	tflog.Info(ctx, "Create resourceDiskSnapshot: got plan successfully", ctxCreateSnpsht)
	tflog.Info(ctx, "Create resourceDiskSnapshot: start creating", ctxCreateSnpsht)

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

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

	// Check if input values are valid in the platform
	_, diags = utilities.DiskSnapshotCheckPresence(ctx, &plan, r.client)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceDiskSnapshot: disk snapshot does not exist")
		return
	}
	tflog.Info(ctx, "Create resourceDiskSnapshot: snapshot successfully loaded", ctxCreateSnpsht)

	if plan.Rollback.ValueBool() { // default is false
		resp.Diagnostics.Append(utilities.RollbackDiskSnapshot(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Create resourceDiskSnapshot: Error rollback snapshot")
			return
		}
	}

	tflog.Info(ctx, "Create resourceDiskSnapshot: resource creation is completed", ctxCreateSnpsht)

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.DiskSnapshotResource(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 *resourceDiskSnapshot) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// Get current state
	var state models.ResourceDiskSnapshotModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceDiskSnapshot: Error get state")
		return
	}
	tflog.Info(ctx, "Read resourceDiskSnapshot: got state successfully", map[string]any{
		"disk_id": state.DiskID.ValueInt64(),
		"label":   state.Label.ValueString(),
	})

	// Set timeouts
	readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout300s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceDiskSnapshot: Error set timeout")
		return
	}
	tflog.Info(ctx, "Read resourceDiskSnapshot: set timeouts successfully", map[string]any{
		"disk_id":     state.DiskID.ValueInt64(),
		"label":       state.Label.ValueString(),
		"readTimeout": readTimeout})

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

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

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

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

	ctxSnpsht := map[string]any{
		"disk_id": plan.DiskID.ValueInt64(),
		"label":   plan.Label.ValueString(),
	}
	tflog.Info(ctx, "Update resourceDiskSnapshot: got plan successfully", ctxSnpsht)

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

	// Set timeouts
	updateTimeout, diags := plan.Timeouts.Update(ctx, constants.Timeout300s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceDiskSnapshot: Error set timeout")
		return
	}
	tflog.Info(ctx, "Update resourceDiskSnapshot: set timeouts successfully", map[string]any{
		"disk_id":       plan.DiskID.ValueInt64(),
		"label":         plan.Label.ValueString(),
		"updateTimeout": updateTimeout})

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

	if !plan.Rollback.Equal(state.Rollback) && plan.Rollback.ValueBool() {
		resp.Diagnostics.Append(utilities.RollbackDiskSnapshot(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceDiskSnapshot: Error rollback snapshot")
			return
		}
	}

	tflog.Info(ctx, "Update resourceDiskSnapshot: disk snapshot update is completed", ctxSnpsht)

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

// Delete deletes the resource and removes the Terraform state on success.
func (r *resourceDiskSnapshot) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.ResourceDiskSnapshotModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceDiskSnapshot: Error get state")
		return
	}
	tflog.Info(ctx, "Delete resourceDiskSnapshot: got state successfully", map[string]any{
		"disk_id": state.DiskID.ValueInt64(),
		"label":   state.Label.ValueString()})

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

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

	// Check if input values are valid in the platform
	_, diags = utilities.DiskSnapshotCheckPresence(ctx, &state, r.client)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceDiskSnapshot: disk snapshot does not exist")
		return
	}

	delReq := disks.SnapshotDeleteRequest{
		DiskID: uint64(state.DiskID.ValueInt64()),
		Label:  state.Label.ValueString(),
	}

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

	tflog.Info(ctx, "End delete resourceDiskSnapshot", map[string]any{
		"disk_id": state.Id.ValueString(),
		"label":   state.Label.ValueString()})
}

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

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

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