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

/**
 * Multi-route general contracts: a contract may reserve quantity across several
 * routes. Each (contract, route, container type) is a row here; drawdown orders
 * reference the route line they drew from via booking_orders.route_line_id.
 */
export class CreateContractRouteLines1820000000001
  implements MigrationInterface
{
  name = 'CreateContractRouteLines1820000000001';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        schema: 'freight',
        name: 'contract_route_lines',
        columns: [
          { name: 'id', type: 'uuid', isPrimary: true, generationStrategy: 'uuid', default: 'gen_random_uuid()' },
          { name: 'contract_booking_id', type: 'uuid' },
          { name: 'origin_yard_id', type: 'uuid' },
          { name: 'destination_yard_id', type: 'uuid' },
          { name: 'container_type_id', type: 'uuid', isNullable: true },
          { name: 'quantity', type: 'numeric', precision: 12, scale: 3 },
          { name: 'created_at', type: 'timestamptz', default: 'now()' },
          { name: 'updated_at', type: 'timestamptz', default: 'now()' },
          { name: 'deleted_at', type: 'timestamptz', isNullable: true },
        ],
        foreignKeys: [
          {
            columnNames: ['contract_booking_id'],
            referencedSchema: 'freight',
            referencedTableName: 'bookings',
            referencedColumnNames: ['id'],
            onDelete: 'CASCADE',
          },
        ],
      }),
      true,
    );

    await queryRunner.createIndex(
      'freight.contract_route_lines',
      new TableIndex({
        name: 'idx_contract_route_lines_contract',
        columnNames: ['contract_booking_id'],
      }),
    );

    await queryRunner.query(
      `ALTER TABLE freight.booking_orders ADD COLUMN IF NOT EXISTS route_line_id uuid;`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `ALTER TABLE freight.booking_orders DROP COLUMN IF EXISTS route_line_id;`,
    );
    await queryRunner.dropTable('freight.contract_route_lines', true);
  }
}
