import { type MigrationInterface, type QueryRunner } from 'typeorm';

/**
 * Tax snapshot columns on every line-item table — quote (4) + booking (4).
 *
 * Per stakeholder policy locked 2026-05-07:
 *   Q1 = C → snapshot on quote save AND re-snapshot at booking-create
 *            from quote (booking save thereafter preserves the row's
 *            existing snapshot)
 *   Q2 = B → snapshot is immutable on edit; explicit "🔄 Refresh Tax"
 *            action re-fetches the current slab. The frozen unit is
 *            the percentage components (CGST/SGST/IGST rates), NOT
 *            the absolute tax_amount — qty/price edits recompute the
 *            amount from `subtotal × frozen_pct` so ordinary edits
 *            still produce correct numbers without disturbing the
 *            rate
 *   Q3 = A → tax computed and displayed in the SELLING currency;
 *            no dual-currency tax columns needed
 *
 * Schema:
 *   tax_breakdown jsonb NULL
 *     Frozen rate components, shape:
 *       { "<tax_type_id>": { "<component_id>": <rate_pct> } }
 *     One outer key per active tax type for the destination (most
 *     tenants will have just GST), inner keys per sub-component.
 *
 *   tax_amount NUMERIC(12,2) NULL
 *     Cached sum of `subtotal × Σ(rate_pcts) / 100`, in selling
 *     currency. Recomputed on every save from the frozen breakdown
 *     so qty/price edits don't drift. Null until first snapshot.
 *
 * Both columns nullable so existing rows continue to work; null
 * tax_breakdown means "no tax recorded for this line" — UI renders
 * "Tax not configured" rather than pretending it's zero.
 */
export class LineItemTaxSnapshot1777700000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    const tables = [
      'query_quote_hotels',
      'query_quote_transports',
      'query_quote_activities',
      'query_quote_specials',
      'booking_hotel_items',
      'booking_transport_items',
      'booking_activity_items',
      'booking_special_items',
    ];
    for (const t of tables) {
      await queryRunner.query(`ALTER TABLE ${t} ADD COLUMN IF NOT EXISTS tax_breakdown jsonb`);
      await queryRunner.query(`ALTER TABLE ${t} ADD COLUMN IF NOT EXISTS tax_amount NUMERIC(12,2)`);
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const tables = [
      'query_quote_hotels',
      'query_quote_transports',
      'query_quote_activities',
      'query_quote_specials',
      'booking_hotel_items',
      'booking_transport_items',
      'booking_activity_items',
      'booking_special_items',
    ];
    for (const t of tables) {
      await queryRunner.query(`ALTER TABLE ${t} DROP COLUMN IF EXISTS tax_amount`);
      await queryRunner.query(`ALTER TABLE ${t} DROP COLUMN IF EXISTS tax_breakdown`);
    }
  }
}
