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

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

	diags := diag.Diagnostics{}

	accountId := uint64(state.AccountID.ValueInt64())

	auditsList, err := utilities.AccountAuditsListDataSourceCheckPresence(ctx, accountId, c)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about account audits with account ID %v", accountId), err.Error())
		return diags
	}

	tflog.Info(ctx, "flattens.AccountAuditsDataSourceList: before flatten", map[string]any{"account_id": accountId})

	id := uuid.New()
	*state = models.DataSourceAccountAuditsListModel{
		AccountID: state.AccountID,
		Timeouts:  state.Timeouts,

		Id: types.StringValue(id.String()),
	}

	items := make([]models.ItemAuditModel, 0, len(*auditsList))
	for _, item := range *auditsList {
		i := 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),
		}
		items = append(items, i)
	}
	state.Items = items

	tflog.Info(ctx, "flattens.AccountAuditsDataSourceList: after flatten", map[string]any{"account_id": state.Id.ValueString()})

	tflog.Info(ctx, "End flattens.AccountAuditsDataSourceList", map[string]any{"account_id": state.Id.ValueString()})
	return nil
}
