import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Cutover cleanup (docs/new-doc.md §17 Phase 4). Runs AFTER the backfill
 * (1823…) so every legacy general contract + drawdown already lives in the
 * `contracts` aggregate.
 *
 * Drops the now-unused booking-as-contract artifacts:
 *   - `bookings.booking_type` (every booking is a real shipment now)
 *   - `bookings.previous_contract_id` (renewal lives on `contracts.renewal_of_id`)
 *   - the `booking_orders` / `booking_order_lines` drawdown ledger
 *   - `contract_route_lines` (superseded by `contract_routes`)
 *
 * The shipment/payment/scheduling/allocation columns on `bookings` are kept —
 * the operational pipeline is unchanged.
 */
export class DropLegacyContractTables1824000000000 implements MigrationInterface {
  name = 'DropLegacyContractTables1824000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    // booking_order_lines references booking_orders → drop child first.
    await queryRunner.query(`DROP TABLE IF EXISTS freight.booking_order_lines CASCADE;`);
    await queryRunner.query(`DROP TABLE IF EXISTS freight.booking_orders CASCADE;`);
    await queryRunner.query(`DROP TABLE IF EXISTS freight.contract_route_lines CASCADE;`);

    await queryRunner.query(`ALTER TABLE freight.bookings DROP COLUMN IF EXISTS booking_type;`);
    await queryRunner.query(`ALTER TABLE freight.bookings DROP COLUMN IF EXISTS previous_contract_id;`);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Re-add the dropped columns (data is not restored — this is a one-way cutover).
    await queryRunner.query(
      `ALTER TABLE freight.bookings ADD COLUMN IF NOT EXISTS booking_type VARCHAR(20) DEFAULT 'ONE_TIME';`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.bookings ADD COLUMN IF NOT EXISTS previous_contract_id UUID;`,
    );
    // The legacy ledger/route tables are intentionally NOT recreated here; restore
    // from a backup if a rollback past the cutover is ever required.
  }
}
