import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Accounting Tier 1 — Customer Tax Invoice store.
 *
 * One row per generated invoice. Sequential per-tenant per-year
 * voucher via the shared settlement_receipt_sequences table with
 * prefix 'INV'. Snapshots guest + destination + line items + tax
 * bifurcation at generation time so the printable invoice stays
 * faithful to "what was billed" even if the booking is edited later.
 *
 * One booking can have multiple invoices (re-issue after itinerary
 * edits). The latest non-void invoice is the canonical "current"
 * one; voided rows stay for audit.
 */
export class CustomerInvoices1782400000000 implements MigrationInterface {
  name = 'CustomerInvoices1782400000000';

  public async up(qr: QueryRunner): Promise<void> {
    await qr.query(`
      CREATE TABLE customer_invoices (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        tenant_id uuid NOT NULL,
        invoice_no varchar(20) NOT NULL,
        invoice_year integer NOT NULL,
        booking_id uuid NOT NULL REFERENCES bookings(id) ON DELETE CASCADE,
        invoice_date date NOT NULL,
        currency_id uuid NOT NULL REFERENCES currencies(id),
        guest_name_snapshot varchar(200),
        guest_mobile_snapshot varchar(50),
        guest_email_snapshot varchar(200),
        destination_name_snapshot varchar(200),
        travel_start_snapshot date,
        travel_end_snapshot date,
        subtotal numeric(12,2) NOT NULL DEFAULT 0,
        tax_total numeric(12,2) NOT NULL DEFAULT 0,
        grand_total numeric(12,2) NOT NULL DEFAULT 0,
        tax_bifurcation jsonb,
        line_items jsonb,
        notes text,
        is_void boolean NOT NULL DEFAULT false,
        voided_at timestamptz,
        voided_by uuid,
        void_reason text,
        is_deleted boolean NOT NULL DEFAULT false,
        created_by uuid,
        updated_by uuid,
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        CONSTRAINT customer_invoices_subtotal_nonneg CHECK (subtotal >= 0),
        CONSTRAINT customer_invoices_tax_total_nonneg CHECK (tax_total >= 0),
        CONSTRAINT customer_invoices_grand_total_nonneg CHECK (grand_total >= 0)
      );
    `);
    await qr.query(`
      CREATE UNIQUE INDEX uq_customer_invoices_tenant_invoice
        ON customer_invoices (tenant_id, invoice_year, invoice_no);
    `);
    await qr.query(`
      CREATE INDEX idx_customer_invoices_tenant_booking
        ON customer_invoices (tenant_id, booking_id, invoice_date DESC);
    `);
    await qr.query(`
      CREATE INDEX idx_customer_invoices_tenant_date
        ON customer_invoices (tenant_id, invoice_date DESC);
    `);
  }

  public async down(qr: QueryRunner): Promise<void> {
    await qr.query(`DROP INDEX IF EXISTS idx_customer_invoices_tenant_date;`);
    await qr.query(`DROP INDEX IF EXISTS idx_customer_invoices_tenant_booking;`);
    await qr.query(`DROP INDEX IF EXISTS uq_customer_invoices_tenant_invoice;`);
    await qr.query(`DROP TABLE IF EXISTS customer_invoices;`);
  }
}
