import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Scope the customs clearance service fee to a direction + route.
 *
 * The fee was a single global flat rate; the business sells it per lane —
 * "import clearance, Djibouti → Adama, 300 USD". CUSTOMS_CLEARANCE rates now
 * carry trade_direction + the yard pair, and contract pricing matches on them
 * strictly (no route-less fallback).
 *
 * Existing route-less clearance rates cannot be backfilled (no way to know
 * which lane each was meant for) — retired exactly like the base-freight
 * retirement in AddRateYardScope: SUPERSEDED + soft-deleted, kept for
 * snapshot history.
 */
export class CustomsClearanceRouteScope2820000000000 implements MigrationInterface {
  name = 'CustomsClearanceRouteScope2820000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      UPDATE freight.rates
      SET status = 'SUPERSEDED',
          deleted_at = now(),
          updated_at = now()
      WHERE deleted_at IS NULL
        AND rate_type = 'CUSTOMS_CLEARANCE'
        AND (origin_yard_id IS NULL OR destination_yard_id IS NULL);
    `);

    await queryRunner.query(
      `ALTER TABLE freight.rates DROP CONSTRAINT IF EXISTS "CK_rates_yard_scope";`,
    );
    await queryRunner.query(`
      ALTER TABLE freight.rates
        ADD CONSTRAINT "CK_rates_yard_scope" CHECK (
          deleted_at IS NOT NULL
          OR status = 'SUPERSEDED'
          OR CASE
               WHEN ("trigger" = 'ALWAYS' AND applies_to IN ('BULK', 'CONTAINER', 'INTERCITY'))
                 OR "trigger" = 'CUSTOMS_CLEARANCE'
                 THEN origin_yard_id IS NOT NULL AND destination_yard_id IS NOT NULL
               ELSE origin_yard_id IS NULL AND destination_yard_id IS NULL
             END
        );
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Retired rates stay retired (their lanes were never recorded); down only
    // restores the pre-customs constraint shape.
    await queryRunner.query(
      `ALTER TABLE freight.rates DROP CONSTRAINT IF EXISTS "CK_rates_yard_scope";`,
    );
    await queryRunner.query(`
      ALTER TABLE freight.rates
        ADD CONSTRAINT "CK_rates_yard_scope" CHECK (
          deleted_at IS NOT NULL
          OR status = 'SUPERSEDED'
          OR CASE
               WHEN "trigger" = 'ALWAYS' AND applies_to IN ('BULK', 'CONTAINER', 'INTERCITY')
                 THEN origin_yard_id IS NOT NULL AND destination_yard_id IS NOT NULL
               ELSE origin_yard_id IS NULL AND destination_yard_id IS NULL
             END
        );
    `);
  }
}
