import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Multi-truck customer (self-haul) assignment. Replaces the single
 * booking.customer_truck_* fields with a per-booking list of trucks, each
 * carrying 1–2 containers and tracking its own arrival. The legacy
 * booking.customer_truck_* columns are kept as a synced booking-level flag
 * (any truck assigned / all trucks arrived) so the warehouse exit-gate and
 * delivery-approval logic keep working.
 */
export class AddCustomerTruckAssignments1950000000000 implements MigrationInterface {
  name = 'AddCustomerTruckAssignments1950000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.customer_truck_assignments (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        booking_id uuid NOT NULL REFERENCES freight.bookings(id) ON DELETE CASCADE,
        plate_number varchar(32) NOT NULL,
        driver_name varchar(120) NOT NULL,
        truck_type varchar(60) NOT NULL,
        assigned_at timestamptz NOT NULL DEFAULT now(),
        arrived_at timestamptz,
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        deleted_at timestamptz
      );
    `);
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS "IDX_customer_truck_assignments_booking" ON freight.customer_truck_assignments (booking_id);`,
    );

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.customer_truck_containers (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        assignment_id uuid NOT NULL REFERENCES freight.customer_truck_assignments(id) ON DELETE CASCADE,
        booking_id uuid NOT NULL REFERENCES freight.bookings(id) ON DELETE CASCADE,
        container_number varchar(64) NOT NULL,
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        deleted_at timestamptz
      );
    `);
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS "IDX_customer_truck_containers_assignment" ON freight.customer_truck_containers (assignment_id);`,
    );
    // One container number can be loaded onto exactly one truck per booking.
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_customer_truck_containers_booking_number"
      ON freight.customer_truck_containers (booking_id, container_number)
      WHERE deleted_at IS NULL;
    `);
  }

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