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

/**
 * A2UI 提交幂等记录：同一 artifact + clientRequestId 只允许执行一次。
 */
export class AddA2UiSubmissions1786001000000 implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    if (await queryRunner.hasTable('ai_a2ui_submissions')) return;
    await queryRunner.createTable(
      new Table({
        name: 'ai_a2ui_submissions',
        columns: [
          { name: 'id', type: 'int', isPrimary: true, isGenerated: true, generationStrategy: 'increment' },
          { name: 'artifact_id', type: 'varchar', length: '100' },
          { name: 'client_request_id', type: 'varchar', length: '36' },
          { name: 'status', type: 'varchar', length: '20' },
          { name: 'result_json', type: 'text', isNullable: true },
          { name: 'created_at', type: 'datetime', default: 'CURRENT_TIMESTAMP' },
        ],
      }),
    );
    await queryRunner.createIndex(
      'ai_a2ui_submissions',
      new TableIndex({
        name: 'uk_ai_a2ui_submissions_artifact_client',
        columnNames: ['artifact_id', 'client_request_id'],
        isUnique: true,
      }),
    );
  }

  async down(queryRunner: QueryRunner): Promise<void> {
    if (await queryRunner.hasTable('ai_a2ui_submissions')) {
      await queryRunner.dropTable('ai_a2ui_submissions');
    }
  }
}
