import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Allow more than one vehicle per first-mile pickup. Junction table joins
 * first_mile ⇄ vehicles, with each truck's container number + actual distance;
 * existing single vehicle_id values are backfilled as the first assignment so
 * nothing is lost. Mirrors the last-mile vehicle-assignment schema.
 */
export class AddFirstMileVehicleAssignments1940000000000 implements MigrationInterface {
  name = "AddFirstMileVehicleAssignments1940000000000";

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

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