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

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

	diags := diag.Diagnostics{}

	rgAudits, err := utilities.RGAuditsCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Cannot get info about resource group audits", err.Error())
		return diags
	}

	tflog.Info(ctx, "flattens.RGAuditsDataSource: before flatten")

	id := uuid.New()
	*state = models.DataSourceRGAuditsModel{
		RGID:     state.RGID,
		Timeouts: state.Timeouts,
		Id:       types.StringValue(id.String()),
	}

	items := make([]models.ItemsRGAuditModel, 0, len(*rgAudits))
	for _, auditItem := range *rgAudits {
		item := models.ItemsRGAuditModel{
			Call:         types.StringValue(auditItem.Call),
			ResponseTime: types.Float64Value(auditItem.ResponseTime),
			StatusCode:   types.Int64Value(int64(auditItem.StatusCode)),
			Timestamp:    types.Float64Value(auditItem.Timestamp),
			User:         types.StringValue(auditItem.User),
		}

		items = append(items, item)
	}
	state.Items = items

	tflog.Info(ctx, "flattens.RGAuditsDataSource: after flatten")

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