// aislop-ignore-file: duplicate-block -- 迁移文件需自包含，表/外键 DDL 声明结构相似
import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm';

/**
 * Unified staged Excel batch-import workflow (v1).
 * import_runs / import_steps / import_rows back the
 * upload → mapping → preview → staged commit → receipt flow.
 */
export class AddImportRuns1784910000000 implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    if (await queryRunner.hasTable('import_runs')) return;

    await queryRunner.createTable(
      new Table({
        name: 'import_runs',
        columns: [
          { name: 'id', type: 'varchar', length: '36', isPrimary: true },
          { name: 'user_id', type: 'integer' },
          { name: 'conversation_id', type: 'integer', isNullable: true },
          { name: 'source', type: 'varchar', length: '10', default: "'manual'" },
          { name: 'file_name', type: 'varchar', length: '255' },
          { name: 'sheets_json', type: 'text' },
          { name: 'status', type: 'varchar', length: '20', default: "'preparing'" },
          { name: 'current_step_key', type: 'varchar', length: '20', isNullable: true },
          { name: 'error', type: 'varchar', length: '500', isNullable: true },
          { name: 'created_at', type: 'datetime', default: 'CURRENT_TIMESTAMP' },
          { name: 'updated_at', type: 'datetime', default: 'CURRENT_TIMESTAMP' },
        ],
        indices: [
          { name: 'idx_import_runs_user_created', columnNames: ['user_id', 'created_at'] },
        ],
      }),
    );

    await queryRunner.createTable(
      new Table({
        name: 'import_steps',
        columns: [
          { name: 'id', type: 'integer', isPrimary: true, isGenerated: true, generationStrategy: 'increment' },
          { name: 'run_id', type: 'varchar', length: '36' },
          { name: 'step_key', type: 'varchar', length: '20' },
          { name: 'sheets_json', type: 'text' },
          { name: 'mapping_json', type: 'text', isNullable: true },
          { name: 'status', type: 'varchar', length: '20', default: "'pending'" },
          { name: 'summary_json', type: 'text', isNullable: true },
          { name: 'committed_at', type: 'datetime', isNullable: true },
          { name: 'created_at', type: 'datetime', default: 'CURRENT_TIMESTAMP' },
        ],
        indices: [
          { name: 'idx_import_steps_run_key', columnNames: ['run_id', 'step_key'] },
        ],
      }),
    );

    await queryRunner.createTable(
      new Table({
        name: 'import_rows',
        columns: [
          { name: 'id', type: 'integer', isPrimary: true, isGenerated: true, generationStrategy: 'increment' },
          { name: 'run_id', type: 'varchar', length: '36' },
          { name: 'step_id', type: 'integer' },
          { name: 'sheet_name', type: 'varchar', length: '200' },
          { name: 'row_number', type: 'integer' },
          { name: 'raw_json', type: 'text' },
          { name: 'normalized_json', type: 'text', isNullable: true },
          { name: 'match_key', type: 'varchar', length: '200', isNullable: true },
          { name: 'action', type: 'varchar', length: '10', isNullable: true },
          { name: 'status', type: 'varchar', length: '20', default: "'pending'" },
          { name: 'errors_json', type: 'text', isNullable: true },
          { name: 'target_id', type: 'integer', isNullable: true },
          { name: 'created_at', type: 'datetime', default: 'CURRENT_TIMESTAMP' },
        ],
        indices: [
          { name: 'idx_import_rows_step', columnNames: ['step_id'] },
          { name: 'idx_import_rows_run_status', columnNames: ['run_id', 'status'] },
        ],
      }),
    );

    await queryRunner.createForeignKey(
      'import_steps',
      new TableForeignKey({
        name: 'fk_import_steps_run',
        columnNames: ['run_id'],
        referencedTableName: 'import_runs',
        referencedColumnNames: ['id'],
        onDelete: 'CASCADE',
      }),
    );
    await queryRunner.createForeignKey(
      'import_rows',
      new TableForeignKey({
        name: 'fk_import_rows_run',
        columnNames: ['run_id'],
        referencedTableName: 'import_runs',
        referencedColumnNames: ['id'],
        onDelete: 'CASCADE',
      }),
    );
  }

  async down(queryRunner: QueryRunner): Promise<void> {
    if (await queryRunner.hasTable('import_rows')) {
      const table = await queryRunner.getTable('import_rows');
      if (table?.foreignKeys.some((fk) => fk.name === 'fk_import_rows_run')) {
        await queryRunner.dropForeignKey('import_rows', 'fk_import_rows_run');
      }
      await queryRunner.dropTable('import_rows');
    }
    if (await queryRunner.hasTable('import_steps')) {
      const table = await queryRunner.getTable('import_steps');
      if (table?.foreignKeys.some((fk) => fk.name === 'fk_import_steps_run')) {
        await queryRunner.dropForeignKey('import_steps', 'fk_import_steps_run');
      }
      await queryRunner.dropTable('import_steps');
    }
    if (await queryRunner.hasTable('import_runs')) {
      await queryRunner.dropTable('import_runs');
    }
  }
}
