import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * 导入向导的 sheets_json 存整表行数据（最多 6 张工作表、数百行），
 * TEXT（64KB）不够用会导致 start_import_wizard 报
 * “Data too long for column 'sheets_json'”，扩容为 MEDIUMTEXT（16MB）。
 */
export class WidenImportSheetsJson1786000000000 implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    if (!(await queryRunner.hasTable('import_runs'))) return;
    const rows = await queryRunner.query(
      `SELECT DATA_TYPE FROM information_schema.COLUMNS
       WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'import_runs' AND COLUMN_NAME = 'sheets_json'`,
    );
    const current = rows?.[0]?.DATA_TYPE as string | undefined;
    if (current && current.toLowerCase() !== 'mediumtext') {
      await queryRunner.query('ALTER TABLE `import_runs` MODIFY COLUMN `sheets_json` MEDIUMTEXT');
    }
  }

  async down(queryRunner: QueryRunner): Promise<void> {
    if (!(await queryRunner.hasTable('import_runs'))) return;
    await queryRunner.query('ALTER TABLE `import_runs` MODIFY COLUMN `sheets_json` TEXT');
  }
}
