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

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

	diags := diag.Diagnostics{}

	resConsList, err := utilities.RGResourceConsumptionListCheckPresence(ctx, c)
	if err != nil {
		diags.AddError("Cannot get info about resource group resource consumption list", err.Error())
		return diags
	}

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

	id := uuid.New()
	*state = models.DataSourceRGResourceConsumptionListModel{
		Timeouts: state.Timeouts,
		Id:       types.StringValue(id.String()),
	}

	items := make([]models.ItemResourceConsumptionModel, 0, len(resConsList.Data))
	for _, resConsItem := range resConsList.Data {
		item := models.ItemResourceConsumptionModel{
			RGID:           types.Int64Value(int64(resConsItem.RGID)),
			Consumed:       flattenResource(ctx, &resConsItem.Consumed),
			Reserved:       flattenResource(ctx, &resConsItem.Reserved),
			ResourceLimits: flattenResourceLimits(ctx, &resConsItem.ResourceLimits),
		}

		items = append(items, item)
	}

	state.Items = items
	state.EntryCount = types.Int64Value(int64(resConsList.EntryCount))

	tflog.Info(ctx, "flattens.RGResourceConsumptionListDataSource: after flatten")

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