package flattens

import (
	"context"
	"fmt"

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

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

	diags := diag.Diagnostics{}

	accountId := uint64(state.AccountID.ValueInt64())

	limits, err := utilities.AccountConsumedUnitsDataSourceCheckPresence(ctx, accountId, c)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about account consumed units with account ID %v", accountId), err.Error())
		return diags
	}

	id := uuid.New()
	*state = models.DataSourceAccountConsumedUnitsModel{
		AccountID: state.AccountID,
		Timeouts:  state.Timeouts,

		Id:       types.StringValue(id.String()),
		CUC:      types.Float64Value(limits.CUC),
		CUD:      types.Float64Value(limits.CUD),
		CUDM:     types.Float64Value(limits.CUDM),
		CUI:      types.Float64Value(limits.CUI),
		CUM:      types.Float64Value(limits.CUM),
		CUNP:     types.Float64Value(limits.CUNP),
		GPUUnits: types.Float64Value(limits.GPUUnits),
	}

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