package utilities

import (
	"context"
	"fmt"

	"github.com/hashicorp/terraform-plugin-framework/diag"
	"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"
)

func AuditListDataSourceCheckPresence(ctx context.Context, state *models.DataSourceAuditList, c *client.Client) (*audit.ListAudits, diag.Diagnostics) {
	tflog.Info(ctx, fmt.Sprintf("AuditListDataSourceCheckPresence: Get info about audit list"))

	diags := diag.Diagnostics{}

	req := audit.ListRequest{}

	if !state.TimestampAt.IsNull() {
		req.TimestampAt = uint64(state.TimestampAt.ValueInt64())
	}
	if !state.TimestampTo.IsNull() {
		req.TimestampTo = uint64(state.TimestampTo.ValueInt64())
	}
	if !state.User.IsNull() {
		req.User = state.User.ValueString()
	}
	if !state.Call.IsNull() {
		req.Call = state.Call.ValueString()
	}
	if !state.MaxStatusCode.IsNull() {
		req.MaxStatusCode = uint64(state.MaxStatusCode.ValueInt64())
	}
	if !state.MinStatusCode.IsNull() {
		req.MinStatusCode = uint64(state.MinStatusCode.ValueInt64())
	}
	if !state.SortBy.IsNull() {
		req.SortBy = state.SortBy.ValueString()
	}
	if !state.Page.IsNull() {
		req.Page = uint64(state.Page.ValueInt64())
	}
	if !state.Size.IsNull() {
		req.Size = uint64(state.Size.ValueInt64())
	}

	recordAuditList, err := c.CloudBroker().Audit().List(ctx, req)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about audit list"), err.Error())
		return nil, diags
	}

	tflog.Info(ctx, "AuditDataSourceCheckPresence: response from CloudBroker().Audit().List", map[string]any{"response": recordAuditList})

	return recordAuditList, nil
}
