import { getDb } from '../client'
import { skills, agentSkills } from '../schema'
import { eq, and, desc, inArray } from 'drizzle-orm'
import { nowExpr } from '../shared/dialect-helpers'

/**
 * Skill Repository。封装 skills 表的所有查询。
 *
 * 设计约定：
 * - 返回类型由 drizzle 推断，消费方不再写 `as Record<string, unknown>`
 * - 删除操作用 db.transaction 级联删 agent_skills（无 FK）
 * - 时间默认值由 schema 的 default 处理，UPDATE 显式刷新用 nowExpr()
 */

export const skillRepo = {
  /** 列出用户的所有 skill，按 updated_at 倒序 */
  listByUser(userId: string) {
    return getDb()
      .select()
      .from(skills)
      .where(eq(skills.userId, userId))
      .orderBy(desc(skills.updatedAt))
      .all()
  },

  /** 按 id + user 查单个 skill */
  findByIdAndUser(id: string, userId: string) {
    return getDb()
      .select()
      .from(skills)
      .where(and(eq(skills.id, id), eq(skills.userId, userId)))
      .get()
  },

  /** 创建 skill，返回新建行。content 默认值用 name 生成 frontmatter 模板 */
  create(data: {
    id: string
    userId: string
    name?: string
    description?: string
    scope?: string
    content?: string
  }) {
    const name = data.name ?? 'New Skill'
    getDb()
      .insert(skills)
      .values({
        id: data.id,
        userId: data.userId,
        name,
        description: data.description ?? '',
        scope: data.scope ?? 'workspace',
        content:
          data.content ??
          `---\ndescription: ${name}\n---\n\n# ${name}\n\nDescribe your skill here.\n`,
      })
      .run()
    return this.findByIdAndUser(data.id, data.userId)
  },

  /** 更新指定字段并刷新 updated_at（WHERE id + user_id），返回更新后行 */
  updateFields(id: string, userId: string, fields: Partial<typeof skills.$inferInsert>) {
    getDb()
      .update(skills)
      .set({ ...fields, updatedAt: nowExpr() })
      .where(and(eq(skills.id, id), eq(skills.userId, userId)))
      .run()
    return this.findByIdAndUser(id, userId)
  },

  /**
   * 删除 skill：事务级联删 agent_skills（替代原 FK CASCADE）。
   * 1. DELETE agent_skills WHERE skill_id（解绑所有 agent）
   * 2. DELETE skill（WHERE id + user_id）
   */
  deleteById(id: string, userId: string) {
    getDb().transaction((tx) => {
      tx.delete(agentSkills).where(eq(agentSkills.skillId, id)).run()
      tx.delete(skills)
        .where(and(eq(skills.id, id), eq(skills.userId, userId)))
        .run()
    })
  },

  /** 校验 user 拥有给定 skillIds 中的哪些，返回实际拥有的 id 列表（用于绑定前的所有权校验） */
  findOwnedIds(userId: string, skillIds: string[]): string[] {
    if (skillIds.length === 0) return []
    const rows = getDb()
      .select({ id: skills.id })
      .from(skills)
      .where(and(eq(skills.userId, userId), inArray(skills.id, skillIds)))
      .all()
    return rows.map((r) => r.id)
  },
}
