package flattens

import (
	"context"

	"github.com/google/uuid"
	"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/cloudapi/disks/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/disks/utilities"
)

// DiskSnapshotDataSource flattens data source for disk snapshot.
// Return error in case data source is not found on the platform.
// Flatten errors are added to tflog.
func DiskSnapshotDataSource(ctx context.Context, state *models.DataSourceDiskSnapshotModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.DiskSnapshotDataSource")

	diskId := uint64(state.DiskID.ValueInt64())

	item, diags := utilities.DataSourceDiskSnapshotCheckPresence(ctx, state, c)
	if diags.HasError() {
		return diags
	}

	tflog.Info(ctx, "flattens.DiskSnapshotDataSource: before flatten", map[string]any{"disk_id": diskId, "snapshot": item})

	id := uuid.New()
	*state = models.DataSourceDiskSnapshotModel{
		DiskID:   state.DiskID,
		Label:    state.Label,
		Timeouts: state.Timeouts,

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

	tflog.Info(ctx, "flattens.DiskSnapshotDataSource: end flatten", map[string]any{
		"disk_id": state.DiskID.ValueInt64(),
		"label":   state.Label.ValueString(),
	})
	return nil
}
