import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Stand the whole wagon fleet in Doraleh.
 *
 * Runs AFTER SeedEdrWagonFleetErNumbering2260000000000, which recreates every
 * wagon with a NULL yard — so this must stay later in timestamp order.
 *
 * A wagon with no yard cannot be coupled to a train (the train builder only
 * offers AVAILABLE wagons standing in the train's own yard), which left the
 * seeded fleet unusable. Doraleh is the Djibouti-side port yard the import runs
 * originate from.
 *
 * The yard is created when absent: environments disagree about which yards
 * exist, so this cannot assume one is there.
 */
const YARD_CODE = 'DORALEH';

export class SeedWagonYardDoraleh2290000000000 implements MigrationInterface {
  name = 'SeedWagonYardDoraleh2290000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Ensure the yard exists and is usable. Deliberately does NOT overwrite an
    // existing label/country — a deployment that already calls this yard
    // something else keeps its own naming.
    await queryRunner.query(
      `
        INSERT INTO freight.yards (code, label, country, is_active, display_order)
        VALUES ($1, 'Doraleh', 'Djibouti', true, 12)
        ON CONFLICT (code) DO UPDATE SET
          is_active  = true,
          deleted_at = NULL,
          updated_at = now();
      `,
      [YARD_CODE],
    );

    const [yard] = await queryRunner.query(
      `SELECT id FROM freight.yards WHERE code = $1 AND deleted_at IS NULL LIMIT 1;`,
      [YARD_CODE],
    );

    if (!yard?.id) {
      throw new Error(`yard_missing:${YARD_CODE}`);
    }

    // Whole fleet — a wagon already coupled to a built train follows the train,
    // so leave those where they stand.
    await queryRunner.query(
      `
        UPDATE freight.wagons
        SET current_yard_id = $1::uuid,
            updated_at      = now()
        WHERE train_id IS NULL;
      `,
      [yard.id],
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Back to the state SeedEdrWagonFleetErNumbering leaves them in.
    await queryRunner.query(`
      UPDATE freight.wagons
      SET current_yard_id = NULL
      WHERE train_id IS NULL;
    `);
  }
}
