import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * arriveSchedule used to release only the primary locomotive of a train set, leaving
 * secondary locomotives ASSIGNED forever. Locomotives are now only ASSIGNED while out
 * on a dispatched train — release every ASSIGNED locomotive that is not attached to a
 * currently-DISPATCHED schedule.
 */
export class ReleaseStuckAssignedLocomotives1861000000001 implements MigrationInterface {
    name = "ReleaseStuckAssignedLocomotives1861000000001";

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`
            UPDATE freight.locomotives l
               SET status = 'AVAILABLE'
             WHERE l.status = 'ASSIGNED'
               AND NOT EXISTS (
                   SELECT 1
                     FROM freight.train_schedules ts
                     JOIN freight.train_sets tset ON tset.id = ts.train_set_id
                     JOIN (
                       SELECT tsl.train_set_id, tsl.locomotive_id
                         FROM freight.train_set_locomotives tsl
                        WHERE tsl.deleted_at IS NULL
                       UNION
                       SELECT t.id AS train_set_id, t.locomotive_id
                         FROM freight.train_sets t
                        WHERE t.locomotive_id IS NOT NULL
                     ) loco ON loco.train_set_id = tset.id
                    WHERE ts.status = 'DISPATCHED'
                      AND ts.deleted_at IS NULL
                      AND loco.locomotive_id = l.id
               );
        `);
    }

    public async down(): Promise<void> {
        // Data fix — not reversible.
    }
}
