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

/**
 * Channel Permission Repository。
 *
 * 封装 channel_permission_links 表的所有查询。permission link 表示
 * (channel_id, chat_id) → agent_id + permission_mode 的权限映射，
 * 用于细粒度控制 IM 消息触发哪个 agent 及其权限模式。
 *
 * 设计约定：
 * - 无独立删除——其生命周期跟随 im_channel，由 imChannelRepo.deleteById 事务级联清理
 * - 返回类型由 drizzle 推断，消费方无需 cast
 * - 该表无 updated_at 字段，权限模式变更用覆盖式更新
 */

export const channelPermissionRepo = {
  /** 按 channel + chat 查 permission link（消息处理时解析 agent 权限） */
  findByChannelAndChat(channelId: string, chatId: string) {
    return getDb()
      .select()
      .from(channelPermissionLinks)
      .where(
        and(
          eq(channelPermissionLinks.channelId, channelId),
          eq(channelPermissionLinks.chatId, chatId),
        ),
      )
      .get()
  },

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

  /** 列出 channel 的全部 permission link */
  listByChannel(channelId: string) {
    return getDb()
      .select()
      .from(channelPermissionLinks)
      .where(eq(channelPermissionLinks.channelId, channelId))
      .orderBy(asc(channelPermissionLinks.createdAt))
      .all()
  },

  /** 创建 permission link */
  create(data: {
    id: string
    channelId: string
    chatId: string
    agentId?: string | null
    permissionMode?: string
  }) {
    getDb()
      .insert(channelPermissionLinks)
      .values({
        id: data.id,
        channelId: data.channelId,
        chatId: data.chatId,
        agentId: data.agentId ?? null,
        permissionMode: data.permissionMode ?? 'confirm',
      })
      .run()
  },

  /** 更新 permission_mode（权限模式切换） */
  updatePermissionMode(id: string, permissionMode: string) {
    getDb()
      .update(channelPermissionLinks)
      .set({ permissionMode })
      .where(eq(channelPermissionLinks.id, id))
      .run()
  },

  /** 更新 agent_id（切换绑定的 agent） */
  updateAgentId(id: string, agentId: string | null) {
    getDb()
      .update(channelPermissionLinks)
      .set({ agentId })
      .where(eq(channelPermissionLinks.id, id))
      .run()
  },

  /** 删除 channel + chat 的 permission link */
  deleteByChannelAndChat(channelId: string, chatId: string) {
    getDb()
      .delete(channelPermissionLinks)
      .where(
        and(
          eq(channelPermissionLinks.channelId, channelId),
          eq(channelPermissionLinks.chatId, chatId),
        ),
      )
      .run()
  },

  /** 删除 channel 的全部 permission link（级联清理用，由 imChannelRepo.deleteById 事务调用） */
  deleteByChannel(channelId: string) {
    getDb()
      .delete(channelPermissionLinks)
      .where(eq(channelPermissionLinks.channelId, channelId))
      .run()
  },

  /** 统计 channel 的 permission link 数量 */
  countByChannel(channelId: string): number {
    const row = getDb()
      .select({ c: sql<number>`count(*)` })
      .from(channelPermissionLinks)
      .where(eq(channelPermissionLinks.channelId, channelId))
      .get()
    return row?.c ?? 0
  },
}
