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

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

	diags := diag.Diagnostics{}

	vinsId := uint64(state.VinsID.ValueInt64())

	audits, diags := utilities.VINSAuditsDataSourceCheckPresence(ctx, vinsId, c)
	if diags.HasError() {
		return diags
	}

	tflog.Info(ctx, "flattens.VINSAuditsDataSource: before flatten", map[string]any{"vins_id": vinsId})

	id := uuid.New()
	*state = models.DataSourceVINSAuditsModel{
		VinsID:   state.VinsID,
		Timeouts: state.Timeouts,

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

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

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