package flattens

import (
	"context"
	"fmt"
	"strings"

	"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/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/disks/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/disks/utilities"
)

// DiskSnapshotResource flattens resource for disk snapshot.
// Return error in case resource is not found on the platform.
// Flatten errors are added to tflog.
func DiskSnapshotResource(ctx context.Context, plan *models.ResourceDiskSnapshotModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.DiskSnapshotResource", map[string]any{
		"disk_id": plan.DiskID.ValueInt64(),
		"label":   plan.Label.ValueString()})

	recordSnapshot, diags := utilities.DiskSnapshotCheckPresence(ctx, plan, c)
	if diags.HasError() {
		return diags
	}

	tflog.Info(ctx, "flattens.DiskSnapshotResource: before flatten", map[string]any{
		"disk_id":    plan.DiskID.ValueInt64(),
		"label":      plan.Label.ValueString(),
		"recordDisk": recordSnapshot})

	id := plan.Id
	if !strings.Contains(id.ValueString(), "#") {
		id = types.StringValue(fmt.Sprintf("%d#%s", plan.DiskID.ValueInt64(), plan.Label.ValueString()))
	}
	*plan = models.ResourceDiskSnapshotModel{
		// required fields
		DiskID: plan.DiskID,
		Label:  types.StringValue(recordSnapshot.Label),

		// optional fields
		Rollback:  plan.Rollback,
		TimeStamp: plan.TimeStamp,
		Timeouts:  plan.Timeouts,

		// computed fields
		Id:          id,
		GUID:        types.StringValue(recordSnapshot.GUID),
		ResID:       types.StringValue(recordSnapshot.ResID),
		SnapSetGUID: types.StringValue(recordSnapshot.SnapSetGUID),
		SnapSetTime: types.Int64Value(int64(recordSnapshot.SnapSetTime)),
	}

	if plan.TimeStamp.IsUnknown() {
		plan.TimeStamp = types.Int64Value(int64(recordSnapshot.Timestamp))
	}

	tflog.Info(ctx, "flattens.DiskResource: after flatten", map[string]any{
		"disk_id": plan.DiskID.ValueInt64(),
		"label":   plan.Label.ValueString()})

	return nil
}
