import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * The customs clearance service fee is no longer prepaid via its own
 * `clearance`-source invoice — it is billed as a CUSTOMS_CLEARANCE line on the
 * booking invoice, together with the freight (see BookingPricingService).
 *
 * - Contracts/bookings parked at the payment gate move straight to the
 *   document step (the gate no longer exists — nothing could ever pay them).
 * - Open (unpaid) clearance invoices are expired; PAID ones stay as history.
 *   NOTE: a ONE_TIME customs contract that already PAID its prepaid fee but
 *   has not booked yet will be billed the fee again on its booking invoice —
 *   accepted for dev data; reverses the old AddClearanceFeePayment migration.
 * - clearance_fee_paid_at columns are dropped from contracts and bookings.
 */
export class DropClearanceFeePrepay2860000000000 implements MigrationInterface {
  name = 'DropClearanceFeePrepay2860000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      UPDATE freight.contracts
      SET status = 'AWAITING_CLEARANCE_DOCUMENTS', updated_at = now()
      WHERE status = 'AWAITING_CLEARANCE_PAYMENT';
    `);
    await queryRunner.query(`
      UPDATE freight.contracts
      SET clearance_status = 'AWAITING_DOCUMENTS', updated_at = now()
      WHERE clearance_status = 'AWAITING_PAYMENT';
    `);
    await queryRunner.query(`
      UPDATE freight.bookings
      SET status = 'AWAITING_DOCUMENTS', updated_at = now()
      WHERE status = 'AWAITING_CLEARANCE_PAYMENT';
    `);
    await queryRunner.query(`
      UPDATE freight.invoices
      SET status = 'EXPIRED', updated_at = now()
      WHERE source = 'clearance'
        AND status IN ('DRAFT', 'ISSUED', 'PENDING', 'PARTIALLY_PAID', 'OVERDUE');
    `);
    await queryRunner.query(
      `ALTER TABLE freight.contracts DROP COLUMN IF EXISTS clearance_fee_paid_at;`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.bookings DROP COLUMN IF EXISTS clearance_fee_paid_at;`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Moved rows and expired invoices stay — only the columns come back.
    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;`,
    );
  }
}
