import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm';

/**
 * Create the freight.last_mile_container_allocations table — container allocation
 * records linking last-mile deliveries with containers and vehicles.
 */
export class CreateLastMileContainerAllocations1810000000002 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    const exists = await queryRunner.hasTable('freight.last_mile_container_allocations');
    if (exists) return;

    await queryRunner.createTable(
      new Table({
        name: 'freight.last_mile_container_allocations',
        columns: [
          {
            name: 'id',
            type: 'uuid',
            isPrimary: true,
            default: 'gen_random_uuid()',
          },
          { name: 'last_mile_id', type: 'uuid', isNullable: false },
          { name: 'container_id', type: 'uuid', isNullable: false },
          { name: 'vehicle_id', type: 'uuid', isNullable: true },
          {
            name: 'container_type',
            type: 'text',
            isNullable: false,
          },
          {
            name: 'quantity',
            type: 'integer',
            default: 1,
            isNullable: false,
          },
          { name: 'created_at', type: 'timestamptz', default: 'now()' },
          { name: 'updated_at', type: 'timestamptz', default: 'now()' },
          { name: 'deleted_at', type: 'timestamptz', isNullable: true },
        ],
      }),
      true,
    );

    await queryRunner.createForeignKey(
      'freight.last_mile_container_allocations',
      new TableForeignKey({
        columnNames: ['last_mile_id'],
        referencedTableName: 'freight.last_mile',
        referencedColumnNames: ['id'],
        onDelete: 'CASCADE',
      }),
    );

    await queryRunner.createForeignKey(
      'freight.last_mile_container_allocations',
      new TableForeignKey({
        columnNames: ['vehicle_id'],
        referencedTableName: 'freight.vehicles',
        referencedColumnNames: ['id'],
        onDelete: 'SET NULL',
      }),
    );

    await queryRunner.query(
      `CREATE INDEX "IDX_last_mile_container_allocations_last_mile_id" ON "freight"."last_mile_container_allocations" ("last_mile_id")`,
    );
    await queryRunner.query(
      `CREATE INDEX "IDX_last_mile_container_allocations_vehicle_id" ON "freight"."last_mile_container_allocations" ("vehicle_id")`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const exists = await queryRunner.hasTable('freight.last_mile_container_allocations');
    if (exists) {
      await queryRunner.dropTable('freight.last_mile_container_allocations');
    }
  }
}
