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

/**
 * Create freight.first_mile_container_allocations table — tracks
 * container allocations per first-mile shipment with optional vehicle assignment.
 */
export class CreateFirstMileContainerAllocations1830000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    const exists = await queryRunner.hasTable('freight.first_mile_container_allocations');
    if (exists) return;

    await queryRunner.createTable(
      new Table({
        name: 'freight.first_mile_container_allocations',
        columns: [
          {
            name: 'id',
            type: 'uuid',
            isPrimary: true,
            default: 'gen_random_uuid()',
          },
          { name: 'first_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: 'int',
            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.first_mile_container_allocations',
      new TableForeignKey({
        columnNames: ['first_mile_id'],
        referencedTableName: 'freight.first_mile',
        referencedColumnNames: ['id'],
        onDelete: 'CASCADE',
      }),
    );

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

    await queryRunner.query(
      `CREATE INDEX "IDX_first_mile_container_allocations_first_mile_id" ON "freight"."first_mile_container_allocations" ("first_mile_id")`,
    );
    await queryRunner.query(
      `CREATE INDEX "IDX_first_mile_container_allocations_vehicle_id" ON "freight"."first_mile_container_allocations" ("vehicle_id")`,
    );
  }

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