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

export class CreateImportDjiboutiOperations1822000000000 implements MigrationInterface {
  name = 'CreateImportDjiboutiOperations1822000000000';

  async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        schema: 'freight',
        name: 'import_djibouti_operations',
        columns: [
          { name: 'id', type: 'uuid', isPrimary: true, generationStrategy: 'uuid', default: 'uuid_generate_v4()' },
          { name: 'train_schedule_id', type: 'uuid', isUnique: true },
          { name: 'documents', type: 'jsonb', default: "'{}'::jsonb" },
          { name: 'gatepass_granted_at', type: 'timestamptz', isNullable: true },
          { name: 'ready_for_loading_at', type: 'timestamptz', isNullable: true },
          { name: 'loaded_on_train_at', type: 'timestamptz', isNullable: true },
          { name: 'departed_from_djibouti_at', type: 'timestamptz', isNullable: true },
          { name: 'load_list_generated_at', type: 'timestamptz', isNullable: true },
          { name: 'performed_by', type: 'varchar', length: '120', isNullable: true },
          { name: 'notes', 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 },
        ],
      }),
      true,
    );

    await queryRunner.createIndex(
      'freight.import_djibouti_operations',
      new TableIndex({
        name: 'idx_import_djibouti_operations_schedule',
        columnNames: ['train_schedule_id'],
      }),
    );

    await queryRunner.createForeignKey(
      'freight.import_djibouti_operations',
      new TableForeignKey({
        columnNames: ['train_schedule_id'],
        referencedTableName: 'train_schedules',
        referencedSchema: 'freight',
        referencedColumnNames: ['id'],
        onDelete: 'CASCADE',
      }),
    );
  }

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