/**
 * Payment Module Types
 * Type definitions for subscriptions, payments, billing, and wallet
 */

// ============================================================================
// Plan Types
// ============================================================================

export type PlanInterval = 'month' | 'year';
export type PlanTier = 'free' | 'basic' | 'pro' | 'premium' | 'enterprise';

// Alineado con financial.subscription_status (DDL)
export type SubscriptionStatus =
  | 'active'
  | 'past_due'
  | 'cancelled'
  | 'canceled' // Alternate spelling for component compatibility
  | 'incomplete'
  | 'trialing'
  | 'unpaid'
  | 'paused';

// Alineado con financial.payment_status (DDL)
export type PaymentStatus =
  | 'pending'
  | 'processing'
  | 'succeeded'
  | 'failed'
  | 'cancelled'
  | 'refunded';

// Alineado con financial.transaction_type (DDL)
export type TransactionType =
  | 'deposit'
  | 'withdrawal'
  | 'transfer_in'
  | 'transfer_out'
  | 'fee'
  | 'refund'
  | 'earning'
  | 'distribution'
  | 'bonus'
  | 'reward' // For gamification/loyalty rewards
  | 'purchase'; // For direct purchases

// Alineado con financial.wallet_status (DDL)
export type WalletStatus = 'active' | 'frozen' | 'closed';

// Alineado con financial.wallet_type (DDL)
export type WalletType = 'trading' | 'investment' | 'earnings' | 'referral';

// Alineado con financial.transaction_status (DDL)
export type TransactionStatus =
  | 'pending'
  | 'processing'
  | 'completed'
  | 'failed'
  | 'cancelled'
  | 'reversed';

// ============================================================================
// Pricing Plan Types
// ============================================================================

export interface PricingPlan {
  id: string;
  name: string;
  slug: string;
  tier: PlanTier;
  description: string;
  priceMonthly: number;
  priceYearly: number;
  stripePriceIdMonthly?: string;
  stripePriceIdYearly?: string;
  features: PlanFeature[];
  limits: PlanLimits;
  isPopular?: boolean;
  isActive: boolean;
}

export interface PlanFeature {
  id: string;
  name: string;
  description?: string;
  included: boolean;
  value?: string | number;
}

export interface PlanLimits {
  maxCourses: number;
  maxApiCalls: number;
  maxPaperTrades: number;
  maxWatchlistSymbols: number;
  mlSignalsAccess: boolean;
  prioritySupport: boolean;
  customAgents: boolean;
}

// ============================================================================
// Subscription Types
// ============================================================================

export interface Subscription {
  id: string;
  userId: string;
  planId: string;
  planName: string;
  planTier: PlanTier;
  status: SubscriptionStatus;
  interval: PlanInterval;
  amount: number;
  currency: string;
  currentPeriodStart: string;
  currentPeriodEnd: string;
  cancelAtPeriodEnd: boolean;
  canceledAt?: string;
  trialEnd?: string;
  stripeSubscriptionId?: string;
  stripeCustomerId?: string;
  createdAt: string;
  updatedAt: string;
}

export interface SubscriptionWithPlan extends Subscription {
  plan: PricingPlan;
}

// ============================================================================
// Payment Types
// ============================================================================

export interface Payment {
  id: string;
  userId: string;
  subscriptionId?: string;
  amount: number;
  currency: string;
  status: PaymentStatus;
  description: string;
  stripePaymentIntentId?: string;
  stripeInvoiceId?: string;
  receiptUrl?: string;
  failureReason?: string;
  createdAt: string;
}

export type PaymentMethodType =
  | 'card'
  | 'bank_account'
  | 'oxxo'
  | 'spei'
  | 'paypal'
  | 'google_pay'
  | 'apple_pay';

export interface PaymentMethod {
  id: string;
  userId: string;
  type: PaymentMethodType;
  brand?: string;
  last4: string;
  expiryMonth?: number;
  expiryYear?: number;
  isDefault: boolean;
  stripePaymentMethodId?: string;
  createdAt: string;
  metadata?: {
    bankName?: string;
    accountType?: string;
    email?: string;
  };
}

export interface InvoiceLineItem {
  id: string;
  description: string;
  quantity: number;
  unitPrice: number;
  amount: number;
}

export interface Invoice {
  id: string;
  subscriptionId?: string;
  number: string;
  amount: number;
  subtotal: number;
  tax: number;
  description?: string;
  lineItems?: InvoiceLineItem[];
  currency: string;
  status: 'draft' | 'open' | 'paid' | 'void' | 'uncollectible';
  periodStart: string;
  periodEnd: string;
  pdfUrl?: string;
  hostedInvoiceUrl?: string;
  dueDate?: string;
  paidAt?: string;
  createdAt: string;
}

// ============================================================================
// Wallet Types
// ============================================================================

export interface Wallet {
  id: string;
  tenantId: string;
  userId: string;
  walletType: WalletType;
  status: WalletStatus;
  balance: number;
  availableBalance: number;
  pendingBalance: number;
  reservedBalance: number;
  currency: string;
  dailyLimit: number;
  monthlyLimit: number;
  dailyUsed: number;
  monthlyUsed: number;
  totalDeposited: number;
  totalWithdrawn: number;
  lastActivityAt?: string;
  metadata?: Record<string, unknown>;
  createdAt: string;
  updatedAt: string;
}

export interface WalletTransaction {
  id: string;
  tenantId: string;
  walletId: string;
  type: TransactionType;
  status: TransactionStatus;
  amount: number;
  balanceBefore: number;
  balanceAfter: number;
  fee: number;
  netAmount: number;
  currency: string;
  description: string;
  referenceId?: string;
  referenceType?: string;
  externalId?: string;
  metadata?: Record<string, unknown>;
  processedAt?: string;
  failureReason?: string;
  createdAt: string;
  updatedAt: string;
}

// ============================================================================
// Checkout Types
// ============================================================================

export interface CouponInfo {
  code: string;
  discountType: 'percentage' | 'fixed';
  discountValue: number;
  isValid: boolean;
  expiresAt?: string;
  maxRedemptions?: number;
  currentRedemptions?: number;
}

export interface CreateSubscriptionInput {
  planId: string;
  interval: PlanInterval;
  paymentMethodId?: string;
  couponCode?: string;
}

export interface CheckoutSession {
  sessionId: string;
  url: string;
  clientSecret?: string;
}

export interface SubscriptionPreview {
  subtotal: number;
  discount: number;
  tax: number;
  total: number;
  currency: string;
  interval: PlanInterval;
  trialDays?: number;
}

// ============================================================================
// Billing Types
// ============================================================================

export interface BillingInfo {
  name: string;
  email: string;
  address?: {
    line1: string;
    line2?: string;
    city: string;
    state?: string;
    postalCode: string;
    country: string;
  };
  taxId?: string;
}

export interface UsageStats {
  apiCalls: UsageStat;
  paperTrades: UsageStat;
  coursesEnrolled: UsageStat;
  watchlistSymbols: UsageStat;
}

export interface UsageStat {
  used: number;
  limit: number;
  percentage: number;
}

// ============================================================================
// API Response Types
// ============================================================================

export interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
  error?: {
    message: string;
    code: string;
  };
}

export interface SubscriptionResponse {
  subscription: Subscription;
  clientSecret?: string;
}

export interface WalletResponse {
  wallet: Wallet;
  recentTransactions: WalletTransaction[];
}

// ============================================================================
// Refund Types
// ============================================================================

export type RefundStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'canceled';

export type RefundReason =
  | 'changed_mind'
  | 'not_needed'
  | 'duplicate_charge'
  | 'service_issue'
  | 'billing_error'
  | 'other';

export interface Refund {
  id: string;
  subscriptionId: string;
  subscriptionName: string;
  invoiceId?: string;
  amount: number;
  currency: string;
  reason: RefundReason;
  reasonDetails?: string;
  status: RefundStatus;
  refundMethod: 'original' | 'wallet';
  requestedAt: string;
  processedAt?: string;
  failureReason?: string;
  transactionId?: string;
  createdAt: string;
  updatedAt: string;
}

export interface RefundEligibility {
  eligible: boolean;
  refundableAmount: number;
  originalAmount: number;
  daysRemaining: number;
  maxRefundDays: number;
  partialRefundAllowed: boolean;
  reason?: string;
}

export interface RefundRequest {
  subscriptionId: string;
  amount: number;
  reason: RefundReason;
  reasonDetails?: string;
  refundMethod: 'original' | 'wallet';
}
