/**
 * Billing Domain - Constants
 *
 * Domain constants for billing validation and business rules.
 */

import type { WhmcsCurrency } from "./providers/whmcs/raw.types";

// ============================================================================
// Currency Defaults
// ============================================================================

/**
 * Single fallback currency for both BFF and Portal when WHMCS currency data
 * is unavailable. This ensures a single source of truth for default currency
 * formatting behaviour.
 */
export const FALLBACK_CURRENCY: WhmcsCurrency = {
  id: 1,
  code: "JPY",
  prefix: "¥",
  suffix: "",
  format: "1",
  rate: "1.00000",
};

// ============================================================================
// Invoice Validation Constants
// ============================================================================

/**
 * Pagination limits for invoice queries
 */
export const INVOICE_PAGINATION = {
  MIN_LIMIT: 1,
  MAX_LIMIT: 100,
  DEFAULT_LIMIT: 10,
  DEFAULT_PAGE: 1,
} as const;

/**
 * Valid invoice statuses for filtering
 * Matches the enum in schema.ts
 */
export const VALID_INVOICE_STATUSES = [
  "Paid",
  "Unpaid",
  "Cancelled",
  "Overdue",
  "Collections",
] as const;

/**
 * Invoice status for list filtering (subset of all statuses)
 */
export const VALID_INVOICE_LIST_STATUSES = [
  "Paid",
  "Unpaid",
  "Cancelled",
  "Overdue",
  "Collections",
] as const;

// ============================================================================
// Validation Helpers
// ============================================================================

/**
 * Check if a status string is valid for invoices
 */
export function isValidInvoiceStatus(status: string): boolean {
  return VALID_INVOICE_STATUSES.includes(status as any);
}

/**
 * Check if pagination limit is within bounds
 */
export function isValidPaginationLimit(limit: number): boolean {
  return limit >= INVOICE_PAGINATION.MIN_LIMIT && limit <= INVOICE_PAGINATION.MAX_LIMIT;
}

/**
 * Sanitize pagination limit to be within bounds
 */
export function sanitizePaginationLimit(limit: number): number {
  return Math.max(
    INVOICE_PAGINATION.MIN_LIMIT,
    Math.min(INVOICE_PAGINATION.MAX_LIMIT, Math.floor(limit))
  );
}

/**
 * Sanitize pagination page to be >= 1
 */
export function sanitizePaginationPage(page: number): number {
  return Math.max(INVOICE_PAGINATION.DEFAULT_PAGE, Math.floor(page));
}

// ============================================================================
// Type Exports
// ============================================================================

export type ValidInvoiceStatus = (typeof VALID_INVOICE_STATUSES)[number];
export type ValidInvoiceListStatus = (typeof VALID_INVOICE_LIST_STATUSES)[number];
