import { getDb } from '../client'
import { wxappConfigs } from '../schema'
import { eq } from 'drizzle-orm'
import { nowExpr } from '../shared/dialect-helpers'

/**
 * Wxapp Config Repository（@reserved — 设计预留，路由未实现）。
 *
 * 类比 h5-page.repo，封装 wxapp_configs 表的基础 CRUD。
 * 后期实现小程序路由时直接使用。
 */

export const wxappConfigRepo = {
  /** 按 slug 查（小程序入口 scene 参数解析用） */
  findBySlug(slug: string) {
    return getDb().select().from(wxappConfigs).where(eq(wxappConfigs.slug, slug)).get()
  },

  /** 按 workspace 查 */
  findByWorkspace(workspaceId: string) {
    return getDb().select().from(wxappConfigs).where(eq(wxappConfigs.workspaceId, workspaceId)).get()
  },

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

  /** 创建配置 */
  create(data: {
    id: string
    workspaceId: string
    slug: string
    appid?: string
    appSecret?: string
    defaultModel?: string
    permissionMode?: string
    pageTitle?: string
    description?: string
    welcomeMessage?: string
    iconEmoji?: string
  }) {
    getDb()
      .insert(wxappConfigs)
      .values({
        id: data.id,
        workspaceId: data.workspaceId,
        slug: data.slug,
        appid: data.appid ?? '',
        appSecret: data.appSecret ?? '',
        defaultModel: data.defaultModel ?? '',
        permissionMode: (data.permissionMode as 'confirm' | 'full') ?? 'full',
        pageTitle: data.pageTitle ?? '',
        description: data.description ?? '',
        welcomeMessage: data.welcomeMessage ?? '',
        iconEmoji: data.iconEmoji ?? '',
      })
      .run()
    return this.findById(data.id)
  },

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

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