package payments

import (
	"context"

	"github.com/google/uuid"
)

// providerAdmin tags an operator-initiated refund in the ledger, distinct from a rail's own refund
// (robokassa / vk / telegram). The refund idempotency key (providerAdmin, order id) allows exactly
// one manual full refund per order.
const providerAdmin = "admin"

// RefundOrderFull refunds a paid order in full at the operator's request: it revokes the funded
// chips best-effort (floored at 0, never negative — D27), records a refund ledger row, and is
// idempotent (a second call reports AlreadyRefunded). The operator performs the actual money refund
// on the rail (Robokassa cabinet / VK support / Telegram refundStarPayment); this records it.
func (s *Service) RefundOrderFull(ctx context.Context, orderID uuid.UUID) (RefundOutcome, error) {
	o, err := s.store.orderByID(ctx, orderID)
	if err != nil {
		return RefundOutcome{}, err
	}
	refunded, err := MoneyFromMinor(o.expectedAmount, Currency(o.currency))
	if err != nil {
		return RefundOutcome{}, err
	}
	return s.store.refund(ctx, orderID, providerAdmin, orderID.String(), refunded, s.clock())
}

// LedgerExportRow is one append-only ledger row for the tax / reconciliation export, carrying the
// account it belongs to alongside the entry fields.
type LedgerExportRow struct {
	AccountID string
	LedgerEntry
}

// LedgerExport reads the entire append-only ledger (all accounts, newest first) for a CSV/JSON
// export — tax reporting and future rail reconciliation. Uncached, admin-only.
func (s *Service) LedgerExport(ctx context.Context) ([]LedgerExportRow, error) {
	return s.store.allLedger(ctx)
}
