/**
 * Billing Types and Interfaces
 *
 * Centralized type definitions for the billing system.
 * All billing-related types should be defined here for consistency.
 */

import type Stripe from "stripe";

// ============================================================================
// BILLING EVENT TYPES
// ============================================================================

/**
 * All possible billing event types tracked in the system.
 * Add new event types here when extending billing functionality.
 */
export const BILLING_EVENT_TYPES = {
  CHECKOUT_COMPLETED: "checkout_completed",
  SETUP_FEE_PAID: "setup_fee_paid",
  INVOICE_PAID: "invoice_paid",
  INVOICE_PAYMENT_FAILED: "invoice_payment_failed",
  PRORATION_PAYMENT: "proration_payment",
  SUBSCRIPTION_CREATED: "subscription_created",
  SUBSCRIPTION_UPDATED: "subscription_updated",
  SUBSCRIPTION_UPGRADED: "subscription_upgraded",
  SUBSCRIPTION_DOWNGRADED: "subscription_downgraded",
  SUBSCRIPTION_CANCELLED: "subscription_cancelled",
  SEATS_UPDATED: "seats_updated",
  CHARGE_REFUNDED: "charge_refunded",
  REFUND_SYNCED: "refund_synced",
} as const;

export type BillingEventType =
  (typeof BILLING_EVENT_TYPES)[keyof typeof BILLING_EVENT_TYPES];

// ============================================================================
// DATA SOURCE TYPES
// ============================================================================

/**
 * Indicates where billing data was retrieved from.
 * - local: From Prisma database only
 * - stripe: From Stripe API only
 * - combined: Local data enriched with Stripe details
 */
export type BillingDataSource = "local" | "stripe" | "combined";

// ============================================================================
// BILLING HISTORY TYPES
// ============================================================================

/**
 * Metadata attached to billing events.
 * Flexible structure to accommodate various event types.
 */
export interface BillingEventMetadata {
  tier_id?: string;
  payment_method_brand?: string;
  payment_method_last_four?: string;
  payment_type?: string;
  from_tier?: string;
  to_tier?: string;
  invoice_number?: string;
  billing_reason?: string;
  period_start?: string | null;
  period_end?: string | null;
  invoice_pdf?: string | null;
  hosted_invoice_url?: string | null;
  seat_quantity?: number;
  [key: string]: unknown;
}

/**
 * A single billing event as returned by the API.
 */
export interface BillingEvent {
  id: string;
  event: string;
  amount: number;
  currency: string;
  createdAt: string;
  metadata?: BillingEventMetadata;
  invoiceId?: string | null;
  paymentIntentId?: string | null;
  invoiceUrl?: string | null;
  invoicePdf?: string | null;
  invoiceStatus?: string | null;
  invoiceNumber?: string | null;
}

/**
 * Response from the billing history API.
 */
export interface BillingHistoryResponse {
  billingHistory: BillingEvent[];
  hasMore: boolean;
  source: BillingDataSource;
}

/**
 * Query parameters for billing history requests.
 */
export interface BillingHistoryQueryParams {
  limit: number;
  includeInvoices: boolean;
}

// ============================================================================
// INVOICE TYPES
// ============================================================================

/**
 * Supported invoice response formats.
 */
export type InvoiceResponseFormat = "json" | "pdf" | "redirect";

/**
 * A single line item on an invoice.
 */
export interface InvoiceLineItem {
  description: string;
  amount: number;
  quantity: number;
  period: {
    start: string;
    end: string;
  } | null;
}

/**
 * Invoice details as returned by the API.
 */
export interface InvoiceDetails {
  id: string;
  number: string | null;
  status: string | null;
  amountPaid: number;
  amountDue: number;
  total: number;
  currency: string;
  hostedUrl: string | null;
  pdfUrl: string | null;
  created: string;
  periodStart: string | null;
  periodEnd: string | null;
  billingReason: string | null;
  customerEmail: string | null;
  lineItems: InvoiceLineItem[];
}

/**
 * Response from the invoice details API.
 */
export interface InvoiceResponse {
  invoice: InvoiceDetails;
}

// ============================================================================
// USER BILLING CONTEXT
// ============================================================================

/**
 * User data relevant to billing operations.
 */
export interface UserBillingContext {
  id: string;
  stripeCustomerId: string | null;
  subscriptions: Array<{
    id: string;
    stripeCustomerId: string | null;
    stripeSubscriptionId?: string | null;
    billing_history?: Array<{
      id: string;
      event: string;
      amount: number;
      currency: string;
      createdAt: Date;
      metadata: unknown;
      invoiceId: string | null;
      paymentIntentId: string | null;
    }>;
  }>;
}

/**
 * Set of Stripe customer IDs associated with a user.
 */
export type CustomerIdSet = Set<string>;

// ============================================================================
// STRIPE INVOICE DETAILS
// ============================================================================

/**
 * Simplified invoice details extracted from Stripe.
 */
export interface StripeInvoiceDetails {
  url: string | null;
  pdf: string | null;
  status: string | null;
  number: string | null;
}

// ============================================================================
// SAVE BILLING HISTORY INPUT
// ============================================================================

/**
 * Input for saving billing history to databases.
 */
export interface SaveBillingHistoryInput {
  id?: string;
  customerId: string;
  subscriptionId?: string;
  invoiceId?: string;
  paymentIntentId?: string;
  event: string;
  amount: number;
  currency: string;
  metadata?: BillingEventMetadata | null;
}

// ============================================================================
// CONSTANTS
// ============================================================================

/**
 * Default and maximum limits for billing history queries.
 */
export const BILLING_HISTORY_LIMITS = {
  DEFAULT: 20,
  MAX: 100,
  INVOICE_ENRICHMENT_MAX: 10,
} as const;

/**
 * Valid subscription statuses for billing queries.
 */
export const ACTIVE_SUBSCRIPTION_STATUSES = [
  "active",
  "trialing",
  "past_due",
  "cancelled",
] as const;

/**
 * Supported currencies.
 */
export const SUPPORTED_CURRENCIES = [
  "qar",
  "gbp",
  "usd",
  "eur",
  "aed",
] as const;

export type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number];
