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

/**
 * A2UI batch-import reviews rendered inside AI assistant messages.
 * One row = one parsed Excel preview; submitted sections are kept for audit.
 */
export class AddA2UiReviews1784880000000 implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    if (await queryRunner.hasTable('ai_reviews')) return;

    await queryRunner.createTable(
      new Table({
        name: 'ai_reviews',
        columns: [
          { name: 'id', type: 'varchar', length: '36', isPrimary: true },
          { name: 'conversation_id', type: 'integer' },
          { name: 'user_id', type: 'integer' },
          { name: 'assistant_message_id', type: 'integer' },
          { name: 'title', type: 'varchar', length: '100' },
          { name: 'summary', type: 'varchar', length: '500', isNullable: true },
          { name: 'sections_json', type: 'text' },
          { name: 'status', type: 'varchar', length: '20', default: "'pending'" },
          { name: 'result_summary', type: 'text', isNullable: true },
          { name: 'submitted_at', type: 'datetime', isNullable: true },
          { name: 'created_at', type: 'datetime', default: 'CURRENT_TIMESTAMP' },
          { name: 'updated_at', type: 'datetime', default: 'CURRENT_TIMESTAMP' },
        ],
        indices: [
          { name: 'idx_ai_reviews_message', columnNames: ['assistant_message_id'] },
          { name: 'idx_ai_reviews_user_status', columnNames: ['user_id', 'status'] },
        ],
      }),
    );

    await queryRunner.createForeignKey(
      'ai_reviews',
      new TableForeignKey({
        name: 'fk_ai_reviews_assistant_message',
        columnNames: ['assistant_message_id'],
        referencedTableName: 'ai_messages',
        referencedColumnNames: ['id'],
        onDelete: 'CASCADE',
      }),
    );
  }

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