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 DataSourceComputeGetAudits(ctx context.Context, state *models.GetAuditsModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start FlattenDataSourceComputeGetAudits")

	diags := diag.Diagnostics{}

	auditsShortList, err := utilities.ComputeGetAuditsCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Error get compute get audits info", err.Error())
		return diags
	}

	id := uuid.New()

	*state = models.GetAuditsModel{
		ComputeID: state.ComputeID,
		Timeouts:  state.Timeouts,
		Id:        types.StringValue(id.String()),
		Items:     flattenItemsShort(ctx, auditsShortList),
	}

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

func flattenItemsShort(ctx context.Context, audits *compute.ListShortAudits) []models.ItemShortAuditModel {
	tflog.Info(ctx, "Start flattenItemsShort")

	res := make([]models.ItemShortAuditModel, 0, len(*audits))
	for _, item := range *audits {
		temp := models.ItemShortAuditModel{
			Epoch:   types.Float64Value(item.Epoch),
			Message: types.StringValue(item.Message),
		}
		res = append(res, temp)
	}

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