import { getDb } from '../client'
import { hooks } from '../schema'
import { eq, sql } from 'drizzle-orm'

/**
 * Hook Repository。封装 hooks 表的所有查询。
 *
 * hooks 表无 user_id（全局共享），无外键；删除操作直接按 id 即可。
 * 字段对应 src/lib/database/schema/sqlite/hooks.ts。
 */
export const hookRepo = {
  /** 列出全部 hook */
  list() {
    return getDb().select().from(hooks).all()
  },

  /** 列出启用的 hook（按 created_at 正序，保证执行顺序稳定） */
  listEnabled() {
    return getDb()
      .select()
      .from(hooks)
      .where(eq(hooks.enabled, 1))
      .all()
  },

  /** 按 id 查单个 hook */
  findById(id: string) {
    return getDb().select().from(hooks).where(eq(hooks.id, id)).get()
  },

  /** 创建 hook（enabled 默认走 schema default=1，event/action/toolPattern/command 同理） */
  create(data: {
    id: string
    name: string
    event?: string
    toolPattern?: string
    action?: 'shell' | 'block' | 'log'
    command?: string
    enabled?: number
  }) {
    getDb()
      .insert(hooks)
      .values({
        id: data.id,
        name: data.name,
        ...(data.event !== undefined ? { event: data.event } : {}),
        ...(data.toolPattern !== undefined ? { toolPattern: data.toolPattern } : {}),
        ...(data.action !== undefined ? { action: data.action } : {}),
        ...(data.command !== undefined ? { command: data.command } : {}),
        ...(data.enabled !== undefined ? { enabled: data.enabled } : {}),
      })
      .run()
  },

  /** 更新指定字段（partial，仅传入字段生效） */
  updateFields(
    id: string,
    fields: Partial<Pick<typeof hooks.$inferInsert, 'name' | 'event' | 'toolPattern' | 'action' | 'command' | 'enabled'>>,
  ) {
    getDb().update(hooks).set(fields).where(eq(hooks.id, id)).run()
  },

  /** 按 id 删除 */
  deleteById(id: string) {
    getDb().delete(hooks).where(eq(hooks.id, id)).run()
  },

  /** 清空全部 hook（/api/data/clear 用） */
  deleteAll() {
    getDb().delete(hooks).run()
  },

  /** 统计总数 */
  count(): number {
    const row = getDb().select({ c: sql<number>`count(*)` }).from(hooks).get()
    return row?.c ?? 0
  },
}
