package flattens

import (
	"context"
	"fmt"

	"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"
)

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

	diags := diag.Diagnostics{}

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

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

	tflog.Info(ctx, "flattens.AccountReservedUnitsDataSource: before flatten", map[string]any{"account_id": accountId, "recordAccount": recordAccount})

	*state = models.DataSourceAccountReservedUnitsModel{
		AccountID: state.AccountID,
		Timeouts:  state.Timeouts,

		CUC:      types.Float64Value(recordAccount.CUC),
		CUD:      types.Float64Value(recordAccount.CUD),
		CUI:      types.Float64Value(recordAccount.CUI),
		CUM:      types.Float64Value(recordAccount.CUM),
		CUDM:     types.Float64Value(recordAccount.CUDM),
		CUNP:     types.Float64Value(recordAccount.CUNP),
		GPUUnits: types.Float64Value(recordAccount.GPUUnits),
	}

	tflog.Info(ctx, "flattens.AccountReservedUnitsDataSource: after flatten", map[string]any{"account_id": state.AccountID.ValueInt64()})

	tflog.Info(ctx, "End flattens.AccountReservedUnitsDataSource", map[string]any{"account_id": state.AccountID.ValueInt64()})
	return nil
}
