import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm';

export const InvoiceStatus = {
  DRAFT: 'draft',
  OPEN: 'open',
  PAID: 'paid',
  PAST_DUE: 'past_due',
  VOID: 'void',
  UNCOLLECTIBLE: 'uncollectible',
} as const;
export type InvoiceStatus = typeof InvoiceStatus[keyof typeof InvoiceStatus];

export const InvoiceCurrency = {
  USD: 'USD',
  CNY: 'CNY',
} as const;
export type InvoiceCurrency = typeof InvoiceCurrency[keyof typeof InvoiceCurrency];

@Entity({ name: 'billing_invoices', schema: 'public' })
export class Invoice {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  @Column({ name: 'tenant_id', type: 'varchar', length: 100 })
  tenantId!: string;

  @Column({ name: 'subscription_id', type: 'uuid', nullable: true })
  subscriptionId?: string;

  @Column({ name: 'invoice_number', type: 'varchar', length: 30, unique: true })
  invoiceNumber!: string; // e.g. INV-2026-03-0001

  @Column({ type: 'varchar', length: 20, default: 'draft' })
  status!: InvoiceStatus;

  @Column({ type: 'varchar', length: 3 })
  currency!: string; // 'USD' | 'CNY'

  @Column({ name: 'subtotal_cents', type: 'int', default: 0 })
  subtotalCents!: number; // in cents/fen

  @Column({ name: 'tax_cents', type: 'int', default: 0 })
  taxCents!: number;

  @Column({ name: 'total_cents', type: 'int', default: 0 })
  totalCents!: number;

  @Column({ name: 'amount_due_cents', type: 'int', default: 0 })
  amountDueCents!: number;

  @Column({ name: 'period_start', type: 'timestamptz' })
  periodStart!: Date;

  @Column({ name: 'period_end', type: 'timestamptz' })
  periodEnd!: Date;

  @Column({ name: 'due_date', type: 'timestamptz' })
  dueDate!: Date;

  @Column({ name: 'paid_at', type: 'timestamptz', nullable: true })
  paidAt?: Date;

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt!: Date;

  @Column({ name: 'updated_at', type: 'timestamptz', nullable: true })
  updatedAt?: Date;
}
