import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * 创建 agent_executions 表
 * 用于持久化每次 Agent 调用的执行记录（类型、耗时、成功/失败）
 * 供 admin 面板的 Agent 调用统计和对话级 Agent 使用明细功能使用
 */
export class AddAgentExecutionsTable1738800000000 implements MigrationInterface {
  name = 'AddAgentExecutionsTable1738800000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "agent_executions" (
        "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        "tenant_id" UUID NOT NULL,
        "conversation_id" UUID NOT NULL,
        "message_id" UUID,
        "user_id" UUID,
        "agent_type" VARCHAR(30) NOT NULL,
        "agent_name" VARCHAR(50) NOT NULL,
        "duration_ms" INT NOT NULL DEFAULT 0,
        "success" BOOLEAN NOT NULL DEFAULT true,
        "error_message" TEXT,
        "tool_calls_count" INT NOT NULL DEFAULT 0,
        "input_tokens" INT NOT NULL DEFAULT 0,
        "output_tokens" INT NOT NULL DEFAULT 0,
        "created_at" TIMESTAMPTZ NOT NULL DEFAULT NOW()
      )
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "idx_agent_executions_tenant"
      ON "agent_executions" ("tenant_id")
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "idx_agent_executions_conversation"
      ON "agent_executions" ("conversation_id")
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "idx_agent_executions_agent_type"
      ON "agent_executions" ("agent_type")
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "idx_agent_executions_created"
      ON "agent_executions" ("created_at")
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "idx_agent_executions_tenant_date"
      ON "agent_executions" ("tenant_id", "created_at")
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_agent_executions_tenant_date"`);
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_agent_executions_created"`);
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_agent_executions_agent_type"`);
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_agent_executions_conversation"`);
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_agent_executions_tenant"`);
    await queryRunner.query(`DROP TABLE IF EXISTS "agent_executions"`);
  }
}
