import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Scope the empty-container return surcharge to a direction + route +
 * container type, like base freight (import-only for now — the box only goes
 * back to the port on imports).
 *
 * Existing route-less RETURN_SURCHARGE rates cannot be backfilled — retired
 * (SUPERSEDED + soft-deleted) exactly like base freight and customs clearance
 * were, kept readable for snapshot history. Route-scoped replacements must be
 * re-entered; a booking that asks for return with no matching rate hard-blocks.
 */
export class ReturnSurchargeRouteScope2830000000000 implements MigrationInterface {
  name = 'ReturnSurchargeRouteScope2830000000000';

  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 = 'RETURN_SURCHARGE'
        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" IN ('CUSTOMS_CLEARANCE', 'WITH_RETURN')
                 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; down only restores the customs-era 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'))
                 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
        );
    `);
  }
}
