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

	diags := diag.Diagnostics{}

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

	id := uuid.New()

	*state = models.ListAuditsModel{
		ComputeID: state.ComputeID,
		Timeouts:  state.Timeouts,
		Id:        types.StringValue(id.String()),
		Items:     flattenItemsAuditsList(ctx, auditsList),
	}

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

func flattenItemsAuditsList(ctx context.Context, audits *compute.ListAudits) []models.ItemAuditModel {
	tflog.Info(ctx, "Start flattenItemsAuditsList")

	res := make([]models.ItemAuditModel, 0, len(*audits))
	for _, item := range *audits {
		temp := models.ItemAuditModel{
			Call:         types.StringValue(item.Call),
			ResponseTime: types.Float64Value(item.ResponseTime),
			StatusCode:   types.Int64Value(int64(item.StatusCode)),
			Timestamp:    types.Float64Value(item.Timestamp),
			User:         types.StringValue(item.User),
		}
		res = append(res, temp)
	}

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