import { getDb } from '../client'
import { agentSkills } from '../schema'
import { eq } from 'drizzle-orm'

/**
 * Agent-Skill Repository。封装 agent_skills 关联表的查询。
 *
 * 设计约定：
 * - agent_skills 无独立删除语义——其生命周期由 agentRepo.deleteById /
 *   skillRepo.deleteById 在事务中级联。本 repo 只暴露关联维护原语。
 * - 返回类型由 drizzle 推断，无需 cast。
 */

export const agentSkillRepo = {
  /** 列出 agent 绑定的 skill_id 列表 */
  listSkillIdsByAgent(agentId: string): string[] {
    const rows = getDb()
      .select({ skillId: agentSkills.skillId })
      .from(agentSkills)
      .where(eq(agentSkills.agentId, agentId))
      .all()
    return rows.map((r) => r.skillId)
  },

  /** 删除 agent 的所有 skill 绑定 */
  deleteAllByAgent(agentId: string) {
    getDb().delete(agentSkills).where(eq(agentSkills.agentId, agentId)).run()
  },

  /** 批量插入绑定（agent_skills 的 PK 为 (agent_id, skill_id)） */
  insertMany(agentId: string, skillIds: string[]) {
    if (skillIds.length === 0) return
    getDb()
      .insert(agentSkills)
      .values(skillIds.map((skillId) => ({ agentId, skillId })))
      .run()
  },

  /** 替换 agent 的全部绑定（事务：先 DELETE 全部再批量 INSERT） */
  replaceByAgent(agentId: string, skillIds: string[]) {
    getDb().transaction((tx) => {
      tx.delete(agentSkills).where(eq(agentSkills.agentId, agentId)).run()
      if (skillIds.length > 0) {
        tx.insert(agentSkills)
          .values(skillIds.map((skillId) => ({ agentId, skillId })))
          .run()
      }
    })
  },
}
