import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Yard country becomes a two-value enum (Ethiopia | Djibouti) and every route
 * freezes its trade direction from the yard countries:
 *   Ethiopia → Djibouti = EXPORT, Djibouti → Ethiopia = IMPORT,
 *   same country = DOMESTIC (shown as "Intercity"; disabled for scheduling
 *   and contracts for now).
 *
 * Existing yard rows are normalized case-insensitively; anything mentioning
 * Djibouti maps there, everything else maps to Ethiopia (the line only serves
 * these two countries). A CHECK constraint keeps future writes honest.
 */
export class YardCountryEnumAndRouteDirection1980000000000 implements MigrationInterface {
  name = 'YardCountryEnumAndRouteDirection1980000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      UPDATE freight.yards
         SET country = CASE
           WHEN lower(trim(country)) LIKE '%djib%' THEN 'Djibouti'
           ELSE 'Ethiopia'
         END
    `);
    await queryRunner.query(`
      ALTER TABLE freight.yards
        DROP CONSTRAINT IF EXISTS chk_yards_country,
        ADD CONSTRAINT chk_yards_country CHECK (country IN ('Ethiopia', 'Djibouti'))
    `);

    await queryRunner.query(`
      ALTER TABLE freight.routes
        ADD COLUMN IF NOT EXISTS direction varchar(10)
    `);
    await queryRunner.query(`
      UPDATE freight.routes r
         SET direction = CASE
           WHEN o.country = 'Djibouti' AND d.country = 'Ethiopia' THEN 'IMPORT'
           WHEN o.country = 'Ethiopia' AND d.country = 'Djibouti' THEN 'EXPORT'
           ELSE 'DOMESTIC'
         END
        FROM freight.yards o, freight.yards d
       WHERE o.id = r.origin_yard_id
         AND d.id = r.destination_yard_id
    `);
    // Orphan origin/destination (deleted yard) — no way to classify; park as
    // DOMESTIC, which is blocked everywhere, so nothing can schedule on it.
    await queryRunner.query(`
      UPDATE freight.routes SET direction = 'DOMESTIC' WHERE direction IS NULL
    `);
    await queryRunner.query(`
      ALTER TABLE freight.routes
        ALTER COLUMN direction SET NOT NULL,
        DROP CONSTRAINT IF EXISTS chk_routes_direction,
        ADD CONSTRAINT chk_routes_direction CHECK (direction IN ('IMPORT', 'EXPORT', 'DOMESTIC'))
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.routes
        DROP CONSTRAINT IF EXISTS chk_routes_direction,
        DROP COLUMN IF EXISTS direction
    `);
    await queryRunner.query(`
      ALTER TABLE freight.yards DROP CONSTRAINT IF EXISTS chk_yards_country
    `);
  }
}
