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

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

	diags := diag.Diagnostics{}

	accountId := uint64(state.AccountID.ValueInt64())
	cuType := state.CUType.ValueString()

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

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

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

		Id:       types.StringValue(id.String()),
		CUResult: types.Float64Value(res),
	}

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