package image

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

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

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

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

// Create the resource and sets the initial Terraform state.
func (r *resourceImageVirtual) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	var plan models.ImageVirtualResourceModel

	// Get plan for create cluster
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error receiving the plan")
		return
	}

	tflog.Info(ctx, "Start create image virtual", map[string]any{"name": plan.ImageName.ValueString()})

	// Set timeouts
	createTimeout, diags := plan.Timeouts.Create(ctx, constants.Timeout600s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error set timeout")
		return
	}

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

	// Create k8s_wg and validated
	resp.Diagnostics.Append(utilities.ResourceImageVirtualCreate(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error create image virtual")
		return
	}

	// Map response body to schema
	resp.Diagnostics.Append(flattens.ResourceImageVirtual(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error flatten image virtual")
		return
	}

	// Set state to fully populated data
	resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error set state")
		return
	}
	tflog.Info(ctx, "End create image virtual", map[string]any{"image_id": plan.ImageId.ValueInt64()})
}

// Read refreshes the Terraform state with the latest data.
func (r *resourceImageVirtual) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	var state models.ImageVirtualResourceModel

	// Get current state
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error get state")
		return
	}

	tflog.Info(ctx, "Start read image virtual", map[string]any{"image_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, "Error set timeout")
		return
	}

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

	imageId, err := strconv.Atoi(state.Id.ValueString())
	if err != nil {
		tflog.Error(ctx, "Cannot convert Id to int value"+err.Error())
	}

	// Read status image virtual
	resp.Diagnostics.Append(utilities.ImageReadStatus(ctx, uint64(imageId), r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error read status")
		return
	}

	// Overwrite items with refreshed state
	resp.Diagnostics.Append(flattens.ResourceImageVirtual(ctx, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error flatten image virtual")
		return
	}

	// Set refreshed state
	resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error set state")
		return
	}
	tflog.Info(ctx, "End read image virtual", map[string]any{"image_id": state.Id.ValueString()})
}

// Update updates the resource and sets the updated Terraform state on success.
func (r *resourceImageVirtual) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
	var plan models.ImageVirtualResourceModel
	var state models.ImageVirtualResourceModel

	// Retrieve values from plan
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error receiving the plan")
		return
	}

	// Retrieve values from state
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error receiving the state")
		return
	}

	tflog.Info(ctx, "Start update image virtual", map[string]any{"image_id": state.ImageId.ValueInt64()})

	// 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
	}

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

	// Update name image virtual
	if !plan.ImageName.Equal(state.ImageName) {
		resp.Diagnostics.Append(utilities.ImageUpdateName(ctx, uint64(state.ImageId.ValueInt64()), plan.ImageName.ValueString(), r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Error update name image virtual")
			return
		}
	}

	// Update link_to image virtual
	if !plan.LinkTo.Equal(state.LinkTo) {
		resp.Diagnostics.Append(utilities.ImageUpdateLink(ctx, uint64(state.ImageId.ValueInt64()), uint64(plan.LinkTo.ValueInt64()), r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Error update link_to image virtual")
			return
		}
	}

	// Map response body to schema
	resp.Diagnostics.Append(flattens.ResourceImageVirtual(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error flatten image virtual")
		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() {
		tflog.Error(ctx, "Error set state")
		return
	}

	tflog.Info(ctx, "End update image virtual", map[string]any{"image_id": plan.ImageId.ValueInt64()})
}

// Delete deletes the resource and removes the Terraform state on success.
func (r *resourceImageVirtual) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.ImageVirtualResourceModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error get state")
		return
	}

	tflog.Info(ctx, "Start delete image virtual", map[string]any{"image_id": state.ImageId.ValueInt64()})

	// Set timeouts
	deleteTimeout, diags := state.Timeouts.Delete(ctx, constants.Timeout300s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Error set timeout")
		return
	}

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

	// Delete image
	_, err := r.client.CloudAPI().Image().Delete(ctx, image.DeleteRequest{ImageID: uint64(state.ImageId.ValueInt64())})
	if err != nil {
		resp.Diagnostics.AddError("Error deleting image virtual with error: ", err.Error())
		return
	}

	tflog.Info(ctx, "End delete image virtual", map[string]any{"image_id": state.ImageId.ValueInt64()})
}

// Schema defines the schema for the resource.
func (r *resourceImageVirtual) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
	resp.Schema = schema.Schema{
		Attributes: schemas.MakeSchemaResourceImageVirtual(),
		Blocks: map[string]schema.Block{
			"timeouts": timeouts.Block(ctx, timeouts.Opts{Create: true, Read: true, Update: true, Delete: true}),
		},
		Version: 1,
	}
}

// Metadata returns the resource type name.
func (r *resourceImageVirtual) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
	resp.TypeName = req.ProviderTypeName + "_image_virtual"
}

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

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