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

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

	diags := diag.Diagnostics{}

	auditGuid := state.AuditGuid.ValueString()

	recordAudit, diags := utilities.AuditDataSourceCheckPresence(ctx, auditGuid, c)
	if diags.HasError() {
		return diags
	}

	tflog.Info(ctx, "flattens.AuditDataSource: before flatten", map[string]any{"audit_guid": auditGuid})

	*state = models.DataSourceAudit{
		AuditGuid: state.AuditGuid,
		Timeouts:  state.Timeouts,

		Arguments:    types.StringValue(recordAudit.Arguments),
		Call:         types.StringValue(recordAudit.Call),
		GUID:         types.StringValue(recordAudit.GUID),
		ID:           types.StringValue(recordAudit.GUID),
		Kwargs:       types.StringValue(recordAudit.Kwargs),
		RemoteAddr:   types.StringValue(recordAudit.RemoteAddr),
		ResponseTime: types.Float64Value(recordAudit.ResponseTime),
		Result:       types.StringValue(recordAudit.Result),
		StatusCode:   types.Int64Value(int64(recordAudit.StatusCode)),
		Tags:         types.StringValue(recordAudit.Tags),
		Timestamp:    types.Float64Value(recordAudit.Timestamp),
		TimestampEnd: types.Float64Value(recordAudit.TimestampEnd),
		User:         types.StringValue(recordAudit.User),
	}

	tflog.Info(ctx, "End flattens.AuditDataSource", map[string]any{"audit_guid": auditGuid})
	return nil
}
