package utilities

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

	"github.com/hashicorp/terraform-plugin-framework/diag"
	"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/service/cloudapi/image/models"
)

func createRequestResourceImageVirtual(ctx context.Context, plan *models.ImageVirtualResourceModel) image.CreateVirtualRequest {
	tflog.Info(ctx, "Start createRequestResourceImageVirtual", map[string]any{"name": plan.ImageName.ValueString()})
	req := image.CreateVirtualRequest{
		Name:     plan.ImageName.ValueString(),
		TargetID: uint64(plan.LinkTo.ValueInt64()),
	}

	tflog.Info(ctx, "End createRequestResourceImageVirtual", map[string]any{"name": plan.ImageName.ValueString()})
	return req
}

func ResourceImageVirtualCreate(ctx context.Context, plan *models.ImageVirtualResourceModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start ResourceImageVirtualCreate", map[string]any{"name": plan.ImageName.ValueString()})

	diags := diag.Diagnostics{}

	// Make request and get response
	imageId, err := c.CloudAPI().Image().CreateVirtual(ctx, createRequestResourceImageVirtual(ctx, plan))
	if err != nil {
		tflog.Error(ctx, "Error response for create image_virtual")
		diags.AddError("Unable to Create image_virtual", err.Error())
		return diags
	}

	plan.Id = types.StringValue(strconv.Itoa(int(imageId)))
	plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))

	tflog.Info(ctx, "End ResourceImageVirtualCreate", map[string]any{"image_id": imageId})
	return nil
}

func ImageUpdateLink(ctx context.Context, imageId, linkTo uint64, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Update link_to image virtual with ID", map[string]any{"image_id": imageId})

	diags := diag.Diagnostics{}

	_, err := c.CloudAPI().Image().Link(ctx, image.LinkRequest{ImageID: imageId, TargetID: linkTo})
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot update link_to image virtual with ID - %d", imageId), err.Error())
		return diags
	}

	tflog.Info(ctx, "Update link_to image virtual successfully", map[string]any{"image_id": imageId})
	return nil
}
