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

export class CreateInterchangeDocuments1821000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        schema: 'freight',
        name: 'interchange_documents',
        columns: [
          { name: 'id', type: 'uuid', isPrimary: true, default: 'uuid_generate_v4()' },
          { name: 'document_no', type: 'varchar', length: '40', isUnique: true },
          { name: 'direction', type: 'varchar', length: '10' },
          { name: 'schedule_id', type: 'uuid', isNullable: true },
          { name: 'train_no', type: 'varchar', length: '40', isNullable: true },
          { name: 'route_id', type: 'uuid', isNullable: true },
          { name: 'origin_facility_id', type: 'uuid', isNullable: true },
          { name: 'destination_facility_id', type: 'uuid', isNullable: true },
          { name: 'handover_location', type: 'varchar', length: '255' },
          { name: 'handover_from', type: 'varchar', length: '255' },
          { name: 'handover_to', type: 'varchar', length: '255' },
          { name: 'operator_name', type: 'varchar', length: '255', isNullable: true },
          { name: 'port_operator_name', type: 'varchar', length: '255', isNullable: true },
          { name: 'shipping_line_name', type: 'varchar', length: '255', isNullable: true },
          { name: 'customs_reference', type: 'varchar', length: '120', isNullable: true },
          { name: 'manifest_reference', type: 'varchar', length: '120', isNullable: true },
          { name: 'status', type: 'varchar', length: '20', default: "'DRAFT'" },
          { name: 'generated_at', type: 'timestamptz', isNullable: true },
          { name: 'acknowledged_at', type: 'timestamptz', isNullable: true },
          { name: 'generated_by', type: 'varchar', length: '120', isNullable: true },
          { name: 'acknowledged_by', type: 'varchar', length: '120', isNullable: true },
          { name: 'remarks', type: 'text', isNullable: true },
          { name: 'created_at', type: 'timestamptz', default: 'now()' },
          { name: 'updated_at', type: 'timestamptz', default: 'now()' },
          { name: 'deleted_at', type: 'timestamptz', isNullable: true },
        ],
        indices: [
          { name: 'idx_interchange_documents_direction', columnNames: ['direction'] },
          { name: 'idx_interchange_documents_status', columnNames: ['status'] },
          { name: 'idx_interchange_documents_schedule', columnNames: ['schedule_id'] },
        ],
      }),
      true,
    );

    await queryRunner.createTable(
      new Table({
        schema: 'freight',
        name: 'interchange_document_items',
        columns: [
          { name: 'id', type: 'uuid', isPrimary: true, default: 'uuid_generate_v4()' },
          { name: 'interchange_document_id', type: 'uuid' },
          { name: 'booking_id', type: 'uuid', isNullable: true },
          { name: 'booking_reference', type: 'varchar', length: '64', isNullable: true },
          { name: 'item_type', type: 'varchar', length: '20' },
          { name: 'booking_container_id', type: 'uuid', isNullable: true },
          { name: 'booking_cargo_id', type: 'uuid', isNullable: true },
          { name: 'container_number', type: 'varchar', length: '64', isNullable: true },
          { name: 'seal_number', type: 'varchar', length: '100', isNullable: true },
          { name: 'cargo_id', type: 'uuid', isNullable: true },
          { name: 'cargo_type', type: 'varchar', length: '255', isNullable: true },
          { name: 'cargo_description', type: 'text', isNullable: true },
          { name: 'weight', type: 'numeric', precision: 14, scale: 3, isNullable: true },
          { name: 'quantity', type: 'numeric', precision: 12, scale: 3, isNullable: true },
          { name: 'package_count', type: 'int', isNullable: true },
          { name: 'wagon_number', type: 'varchar', length: '80', isNullable: true },
          { name: 'condition_status', type: 'varchar', length: '20', default: "'GOOD'" },
          { name: 'damage_description', type: 'text', isNullable: true },
          { name: 'remarks', type: 'text', isNullable: true },
          { name: 'created_at', type: 'timestamptz', default: 'now()' },
          { name: 'updated_at', type: 'timestamptz', default: 'now()' },
          { name: 'deleted_at', type: 'timestamptz', isNullable: true },
        ],
        foreignKeys: [
          {
            columnNames: ['interchange_document_id'],
            referencedSchema: 'freight',
            referencedTableName: 'interchange_documents',
            referencedColumnNames: ['id'],
            onDelete: 'CASCADE',
          },
          {
            columnNames: ['booking_id'],
            referencedSchema: 'freight',
            referencedTableName: 'bookings',
            referencedColumnNames: ['id'],
            onDelete: 'SET NULL',
          },
        ],
        indices: [
          { name: 'idx_interchange_items_document', columnNames: ['interchange_document_id'] },
          { name: 'idx_interchange_items_booking', columnNames: ['booking_id'] },
        ],
      }),
      true,
    );

    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS uq_interchange_active_schedule_direction
      ON freight.interchange_documents(schedule_id, direction)
      WHERE schedule_id IS NOT NULL AND status <> 'CANCELLED' AND deleted_at IS NULL;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query('DROP INDEX IF EXISTS freight.uq_interchange_active_schedule_direction;');
    await queryRunner.dropTable('freight.interchange_document_items', true);
    await queryRunner.dropTable('freight.interchange_documents', true);
  }
}
