import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Allow more than one vehicle per last-mile delivery. Junction table joins
 * last_mile ⇄ vehicles; existing single vehicle_id values are backfilled as
 * the first assignment so nothing is lost.
 */
export class AddLastMileVehicleAssignments1890000000004 implements MigrationInterface {
  name = "AddLastMileVehicleAssignments1890000000004";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.last_mile_vehicle_assignments (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        last_mile_id uuid NOT NULL REFERENCES freight.last_mile(id) ON DELETE CASCADE,
        vehicle_id uuid NOT NULL REFERENCES freight.vehicles(id),
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        deleted_at timestamptz,
        CONSTRAINT "UQ_LAST_MILE_VEHICLE" UNIQUE (last_mile_id, vehicle_id)
      )
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_LM_VEHICLE_ASSIGNMENTS_VEHICLE"
      ON freight.last_mile_vehicle_assignments (vehicle_id)
    `);
    // Backfill: existing single-vehicle assignments become the first row
    await queryRunner.query(`
      INSERT INTO freight.last_mile_vehicle_assignments (last_mile_id, vehicle_id)
      SELECT id, vehicle_id FROM freight.last_mile
      WHERE vehicle_id IS NOT NULL AND deleted_at IS NULL
      ON CONFLICT (last_mile_id, vehicle_id) DO NOTHING
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE IF EXISTS freight.last_mile_vehicle_assignments`);
  }
}
