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

/**
 * Per-document GL review for the post-counter-sign clearance gate. One row per
 * required clearance document; GL marks each APPROVED or QUERIED before the
 * booking can proceed to operations.
 */
export class CreateBookingDocumentReview1820000000002
  implements MigrationInterface
{
  name = 'CreateBookingDocumentReview1820000000002';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        schema: 'freight',
        name: 'booking_document_review',
        columns: [
          { name: 'id', type: 'uuid', isPrimary: true, generationStrategy: 'uuid', default: 'gen_random_uuid()' },
          { name: 'booking_id', type: 'uuid' },
          { name: 'setting_code', type: 'varchar', length: '128' },
          { name: 'file_key', type: 'varchar', length: '128' },
          { name: 'file_record_id', type: 'uuid', isNullable: true },
          { name: 'status', type: 'varchar', length: '20', default: "'PENDING'" },
          { name: 'note', type: 'text', isNullable: true },
          { name: 'reviewed_by_staff_id', type: 'uuid', isNullable: true },
          { name: 'reviewed_at', type: 'timestamptz', 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: ['booking_id'],
            referencedSchema: 'freight',
            referencedTableName: 'bookings',
            referencedColumnNames: ['id'],
            onDelete: 'CASCADE',
          },
        ],
      }),
      true,
    );

    await queryRunner.createIndex(
      'freight.booking_document_review',
      new TableIndex({ name: 'idx_booking_document_review_booking', columnNames: ['booking_id'] }),
    );
    await queryRunner.createIndex(
      'freight.booking_document_review',
      new TableIndex({ name: 'idx_booking_document_review_status', columnNames: ['status'] }),
    );
    await queryRunner.createIndex(
      'freight.booking_document_review',
      new TableIndex({
        name: 'uq_booking_document_review_doc',
        columnNames: ['booking_id', 'setting_code', 'file_key'],
        isUnique: true,
      }),
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropTable('freight.booking_document_review', true);
  }
}
