import { DataSource } from 'typeorm';
import { AddA2UiReviews1784880000000 } from '../migrations/1784880000000-AddA2UiReviews';
import { EnlargeAiReviewSections1784900000000 } from '../migrations/1784900000000-EnlargeAiReviewSections';

describe('EnlargeAiReviewSections1784900000000', () => {
  let dataSource: DataSource;

  beforeEach(async () => {
    dataSource = new DataSource({
      type: 'better-sqlite3',
      database: ':memory:',
      migrations: [AddA2UiReviews1784880000000, EnlargeAiReviewSections1784900000000],
    });
    await dataSource.initialize();
    await dataSource.query(`
      CREATE TABLE ai_messages (
        id integer PRIMARY KEY AUTOINCREMENT,
        conversation_id integer NOT NULL,
        role varchar(20) NOT NULL,
        content text,
        reasoning_content text,
        status varchar(20) NOT NULL,
        error_code varchar(50),
        reply_to_message_id integer,
        feedback varchar(10),
        feedback_reason varchar(500),
        metadata text,
        created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
      )
    `);
  });

  afterEach(async () => {
    if (dataSource.isInitialized) await dataSource.destroy();
  });

  it('迁移后可保存远超 256KB 的预览数据，且再次执行幂等', async () => {
    await dataSource.runMigrations();
    await dataSource.runMigrations();

    await dataSource.query(
      `INSERT INTO ai_messages (conversation_id, role, content, status)
       VALUES (1, 'assistant', '', 'completed')`,
    );
    const big = '中'.repeat(300 * 1024);
    await dataSource.query(
      `INSERT INTO ai_reviews
        (id, conversation_id, user_id, assistant_message_id, title, sections_json, status)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      ['review-1', 1, 1, 1, '大体积导入', big, 'pending'],
    );
    const rows: Array<{ sections_json: string }> = await dataSource.query(
      'SELECT sections_json FROM ai_reviews WHERE id = ?',
      ['review-1'],
    );
    expect(rows[0].sections_json.length).toBe(big.length);

    const runner = dataSource.createQueryRunner();
    expect(await runner.hasColumn('ai_reviews', 'sections_json')).toBe(true);
    await runner.release();
  });
});
