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

/**
 * Create the freight.first_mile table — one row per booking's first-mile
 * (door → terminal) leg, with payment split and an optional assigned vehicle.
 */
export class CreateFirstMile1810000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    const exists = await queryRunner.hasTable('freight.first_mile');
    if (exists) return;

    await queryRunner.createTable(
      new Table({
        name: 'freight.first_mile',
        columns: [
          {
            name: 'id',
            type: 'uuid',
            isPrimary: true,
            default: 'gen_random_uuid()',
          },
          { name: 'booking_id', type: 'uuid', isNullable: false },
          {
            name: 'status',
            type: 'varchar',
            length: '30',
            default: `'PAYMENT_PENDING'`,
            isNullable: false,
          },
          {
            name: 'advanced_payment',
            type: 'numeric',
            precision: 14,
            scale: 2,
            default: 0,
            isNullable: false,
          },
          {
            name: 'remaining_payment',
            type: 'numeric',
            precision: 14,
            scale: 2,
            default: 0,
            isNullable: false,
          },
          {
            name: 'estimated_km',
            type: 'numeric',
            precision: 10,
            scale: 2,
            isNullable: true,
          },
          {
            name: 'exact_km',
            type: 'numeric',
            precision: 10,
            scale: 2,
            isNullable: true,
          },
          { name: 'vehicle_id', type: 'uuid', isNullable: true },
          { 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',
      new TableForeignKey({
        columnNames: ['booking_id'],
        referencedTableName: 'freight.bookings',
        referencedColumnNames: ['id'],
        onDelete: 'CASCADE',
      }),
    );

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

    await queryRunner.query(
      `CREATE INDEX "IDX_first_mile_booking_id" ON "freight"."first_mile" ("booking_id")`,
    );
    await queryRunner.query(
      `CREATE INDEX "IDX_first_mile_status" ON "freight"."first_mile" ("status")`,
    );
    await queryRunner.query(
      `CREATE INDEX "IDX_first_mile_vehicle_id" ON "freight"."first_mile" ("vehicle_id")`,
    );
  }

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