package flattens

import (
	"context"
	"fmt"

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

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

	diags := diag.Diagnostics{}

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

	snapshots, err := utilities.DiskSnapshotListCheckPresence(ctx, diskId, c)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about disk snapshot list with disk ID %v", diskId), err.Error())
		return diags
	}

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

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

		// computed fields
		Id: types.StringValue(id.String()),
	}

	res := make([]models.DiskItemSnapshot, 0, len(*snapshots))
	for _, item := range *snapshots {
		temp := models.DiskItemSnapshot{
			GUID:        types.StringValue(item.GUID),
			Label:       types.StringValue(item.Label),
			ResID:       types.StringValue(item.ResID),
			ReferenceID: types.StringValue(item.ReferenceID),
			SnapSetGUID: types.StringValue(item.SnapSetGUID),
			SnapSetTime: types.Int64Value(int64(item.SnapSetTime)),
			TimeStamp:   types.Int64Value(int64(item.Timestamp)),
		}
		res = append(res, temp)
	}

	state.Items = res

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