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/decort-golang-sdk/pkg/cloudapi/compute"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/kvmvm/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/kvmvm/utilities"
)

func DataSourceComputeSnapshotUsage(ctx context.Context, state *models.ListSnapShotsModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start FlattenDataSourceComputeSnapshotUsage")

	diags := diag.Diagnostics{}

	snapshotUsage, err := utilities.ComputeSnapshotUsageCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Error get compute snapshot usage info", err.Error())
		return diags
	}

	id := uuid.New()

	*state = models.ListSnapShotsModel{
		ComputeID: state.ComputeID,
		Label:     state.Label,
		Timeouts:  state.Timeouts,
		Id:        types.StringValue(id.String()),
		Items:     flattenItemsSnapshotUsage(ctx, snapshotUsage),
	}

	tflog.Info(ctx, "End FlattenDataSourceComputeSnapshotUsage")
	return nil
}

func flattenItemsSnapshotUsage(ctx context.Context, snapshot *compute.ListUsageSnapshots) []models.ItemUsageSnapshotModel {
	tflog.Info(ctx, "Start flattenItemsSnapshotUsage")

	res := make([]models.ItemUsageSnapshotModel, 0, len(*snapshot))
	for _, item := range *snapshot {
		temp := models.ItemUsageSnapshotModel{
			Count:     types.Int64Value(int64(item.Count)),
			Stored:    types.Float64Value(float64(item.Stored)),
			Label:     types.StringValue(item.Label),
			Timestamp: types.Int64Value(int64(item.Timestamp)),
		}
		res = append(res, temp)
	}

	tflog.Info(ctx, "End flattenItemsSnapshotUsage")
	return res
}
