package flattens

import (
	"context"

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

func AuditListDataSource(ctx context.Context, state *models.DataSourceAuditList, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.AuditListDataSource")

	diags := diag.Diagnostics{}

	recordAuditList, diags := utilities.AuditListDataSourceCheckPresence(ctx, state, c)
	if diags.HasError() {
		return diags
	}

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

	*state = models.DataSourceAuditList{
		TimestampAt:   state.TimestampAt,
		TimestampTo:   state.TimestampTo,
		User:          state.User,
		Call:          state.Call,
		MinStatusCode: state.MinStatusCode,
		MaxStatusCode: state.MaxStatusCode,
		SortBy:        state.SortBy,
		Page:          state.Page,
		Size:          state.Size,
		Timeouts:      state.Timeouts,

		EntryCount: types.Int64Value(int64(recordAuditList.EntryCount)),
		Items:      flattenAuditItems(ctx, recordAuditList.Data),
	}

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

func flattenAuditItems(ctx context.Context, auditList []audit.ItemAudit) []models.ItemAudit {
	tflog.Info(ctx, "Start flattenAuditItems")

	res := make([]models.ItemAudit, 0, len(auditList))

	for _, item := range auditList {
		temp := models.ItemAudit{
			Call:         types.StringValue(item.Call),
			GUID:         types.StringValue(item.GUID),
			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 flattenAuditItems")
	return res
}
