import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Prepaid customs clearance service fee (Path B):
 *  - contract_rate_snapshots.is_clearance — flags the frozen CUSTOMS_CLEARANCE
 *    fee line so it is billed via its own clearance invoice and excluded from
 *    shipment booking totals;
 *  - contracts.clearance_fee_paid_at — when the ONE_TIME contract-level fee
 *    settled (gate: AWAITING_CLEARANCE_PAYMENT → AWAITING_CLEARANCE_DOCUMENTS);
 *  - bookings.clearance_fee_paid_at — when a GENERAL shipment-request instance's
 *    fee settled (gate: AWAITING_CLEARANCE_PAYMENT → AWAITING_DOCUMENTS).
 * All nullable/defaulted — existing rows are untouched and keep today's flow.
 */
export class AddClearanceFeePayment2260000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.contract_rate_snapshots
        ADD COLUMN IF NOT EXISTS is_clearance BOOLEAN NOT NULL DEFAULT FALSE;
    `);
    await queryRunner.query(`
      ALTER TABLE freight.contracts
        ADD COLUMN IF NOT EXISTS clearance_fee_paid_at TIMESTAMPTZ;
    `);
    await queryRunner.query(`
      ALTER TABLE freight.bookings
        ADD COLUMN IF NOT EXISTS clearance_fee_paid_at TIMESTAMPTZ;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.bookings
        DROP COLUMN IF EXISTS clearance_fee_paid_at;
    `);
    await queryRunner.query(`
      ALTER TABLE freight.contracts
        DROP COLUMN IF EXISTS clearance_fee_paid_at;
    `);
    await queryRunner.query(`
      ALTER TABLE freight.contract_rate_snapshots
        DROP COLUMN IF EXISTS is_clearance;
    `);
  }
}
