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

/**
 * A2UI dynamic forms rendered inside AI assistant messages.
 * Each row is one rendered form; submitted values are kept for audit.
 */
export class AddA2UiForms1784870000000 implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    if (await queryRunner.hasTable('ai_forms')) return;

    await queryRunner.createTable(
      new Table({
        name: 'ai_forms',
        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: '50' },
          { name: 'description', type: 'varchar', length: '200', isNullable: true },
          { name: 'submit_label', type: 'varchar', length: '20', default: "'提交'" },
          { name: 'fields_json', type: 'text' },
          { name: 'status', type: 'varchar', length: '20', default: "'pending'" },
          { name: 'submitted_values_json', 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_forms_message', columnNames: ['assistant_message_id'] },
          { name: 'idx_ai_forms_user_status', columnNames: ['user_id', 'status'] },
        ],
      }),
    );

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

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