import { getDb } from '../client'
import { h5Pages, workspaces } from '../schema'
import { eq, and, asc } from 'drizzle-orm'
import { nowExpr } from '../shared/dialect-helpers'

/**
 * H5 Page Repository。
 *
 * 封装 h5_pages 表的所有查询。owner_user_id 不在此表冗余：
 * 由 workspaceId → workspaces.owner_user_id 反查（resolveOwnerUserIdByWorkspace）。
 *
 * 设计对齐 im-channel.repo：
 * - findById / findByIdAndWorkspace / findBySlug / findByWorkspace / listByOwner
 * - create / updateFields / regenerateSlug / deleteById
 */

/** h5_pages 全列 selection */
const h5PageColumns = {
  id: h5Pages.id,
  workspaceId: h5Pages.workspaceId,
  slug: h5Pages.slug,
  appSecrets: h5Pages.appSecrets,
  defaultModel: h5Pages.defaultModel,
  permissionMode: h5Pages.permissionMode,
  pageTitle: h5Pages.pageTitle,
  assistantName: h5Pages.assistantName,
  description: h5Pages.description,
  welcomeMessage: h5Pages.welcomeMessage,
  iconEmoji: h5Pages.iconEmoji,
  enabled: h5Pages.enabled,
  createdAt: h5Pages.createdAt,
  updatedAt: h5Pages.updatedAt,
}

export const h5PageRepo = {
  /** 按 id 查（不限 owner，内部流程用） */
  findById(id: string) {
    return getDb().select().from(h5Pages).where(eq(h5Pages.id, id)).get()
  },

  /** 按 slug 查（H5 入口路由 /h5/[slug] 用） */
  findBySlug(slug: string) {
    return getDb().select().from(h5Pages).where(eq(h5Pages.slug, slug)).get()
  },

  /** 按 workspace 查（H5View 跟随 activeWorkspaceId） */
  findByWorkspace(workspaceId: string) {
    return getDb().select().from(h5Pages).where(eq(h5Pages.workspaceId, workspaceId)).get()
  },

  /** 按 id + workspace 查（owner 配置 PATCH/DELETE 鉴权：必须是该 workspace 的 owner） */
  findByIdAndWorkspace(id: string, workspaceId: string) {
    return getDb()
      .select()
      .from(h5Pages)
      .where(and(eq(h5Pages.id, id), eq(h5Pages.workspaceId, workspaceId)))
      .get()
  },

  /** 列出 owner 的全部 H5 页面（通过 workspace 反查），按 created_at 升序 */
  listByOwner(ownerUserId: string) {
    return getDb()
      .select(h5PageColumns)
      .from(h5Pages)
      .innerJoin(workspaces, eq(h5Pages.workspaceId, workspaces.id))
      .where(eq(workspaces.ownerUserId, ownerUserId))
      .orderBy(asc(h5Pages.createdAt))
      .all()
  },

  /** 创建 H5 页面 */
  create(data: {
    id: string
    workspaceId: string
    slug: string
    defaultModel?: string
    permissionMode?: 'confirm' | 'full'
    pageTitle?: string
    assistantName?: string
    description?: string
    welcomeMessage?: string
    iconEmoji?: string
    enabled?: number
  }) {
    getDb()
      .insert(h5Pages)
      .values({
        id: data.id,
        workspaceId: data.workspaceId,
        slug: data.slug,
        defaultModel: data.defaultModel ?? '',
        permissionMode: data.permissionMode ?? 'full',
        pageTitle: data.pageTitle ?? '',
        assistantName: data.assistantName ?? '',
        description: data.description ?? '',
        welcomeMessage: data.welcomeMessage ?? '',
        iconEmoji: data.iconEmoji ?? '',
        enabled: data.enabled ?? 1,
      })
      .run()
    return this.findById(data.id)
  },

  /** 更新指定字段并刷新 updated_at */
  updateFields(id: string, fields: Partial<typeof h5Pages.$inferInsert>) {
    getDb()
      .update(h5Pages)
      .set({ ...fields, updatedAt: nowExpr() })
      .where(eq(h5Pages.id, id))
      .run()
    return this.findById(id)
  },

  /** 重新生成 slug（地址泄漏兜底） */
  regenerateSlug(id: string, newSlug: string) {
    getDb()
      .update(h5Pages)
      .set({ slug: newSlug, updatedAt: nowExpr() })
      .where(eq(h5Pages.id, id))
      .run()
    return this.findById(id)
  },

  /** 删除（ON DELETE CASCADE 由 FK 处理 workspaces 删除时的级联；显式按 id 删） */
  deleteById(id: string) {
    getDb().delete(h5Pages).where(eq(h5Pages.id, id)).run()
  },

  /**
   * 反查 workspace 的 owner_user_id（H5 入口签 cookie 时用）。
   * 对应 ChannelRouter.getChannelOwnerUserId() 的作用。
   * 返回空串表示 workspace 不存在或无 owner。
   */
  resolveOwnerUserIdByWorkspace(workspaceId: string): string {
    const row = getDb()
      .select({ ownerUserId: workspaces.ownerUserId })
      .from(workspaces)
      .where(eq(workspaces.id, workspaceId))
      .get()
    return row?.ownerUserId ?? ''
  },

  /** 检查 slug 是否已被占用（regenerateSlug 前用） */
  slugExists(slug: string): boolean {
    const row = getDb()
      .select({ id: h5Pages.id })
      .from(h5Pages)
      .where(eq(h5Pages.slug, slug))
      .get()
    return row !== undefined
  },
}
