import { rpcOrNull, rpcOrValue } from '@/services/analytics/rpc.uts'

/**
 * DIY 页面模型
 */
export type DiyPage = {
  id: string
  name: string
  type: string
  config: UTSJSONObject
  is_home: boolean
  is_active: boolean
  created_at: string
  updated_at: string
}

/**
 * 获取 DIY 页面分页列表
 */
export async function fetchDiyPageList(
  search: string | null = null,
  type: string | null = null,
  page: number = 1,
  pageSize: number = 20
): Promise<{ total: number, items: Array<DiyPage> }> {
  const res = await rpcOrNull('rpc_admin_get_diy_page_list', {
    p_search: search,
    p_type: type,
    p_page: page,
    p_page_size: pageSize
  } as UTSJSONObject)

  if (res == null) return { total: 0, items: [] as Array<DiyPage> }
  
  return {
    total: (res as any).total as number,
    items: (res as any).items as Array<DiyPage>
  }
}

/**
 * 保存 DIY 页面配置
 */
export async function saveDiyPage(
  id: string | null,
  name: string,
  type: string,
  config: UTSJSONObject,
  isActive: boolean = true
): Promise<string | null> {
  const res = await rpcOrValue('rpc_admin_save_diy_page', {
    p_id: id,
    p_name: name,
    p_type: type,
    p_config: config,
    p_is_active: isActive
  } as any)
  
  return res != null ? String(res) : null
}

/**
 * 删除 DIY 页面
 */
export async function deleteDiyPage(id: string): Promise<boolean> {
  const ok = await rpcOrValue('rpc_admin_delete_diy_page', { p_id: id } as any)
  return ok === true
}

/**
 * 设置为生效首页
 */
export async function setAsHomePage(id: string): Promise<boolean> {
  const ok = await rpcOrValue('rpc_admin_set_home_page', { p_id: id } as any)
  return ok === true
}

/**
 * 获取特定类型的生效配置 (供预览或样式页使用)
 * 逻辑：从列表接口过滤 type 且 is_home = true 的第一项
 */
export async function getActiveDiyConfig(type: string): Promise<DiyPage | null> {
  // 由于目前没有单独的 get_active_config RPC，复用 list 接口并按 type 筛选
  const res = await fetchDiyPageList(null, type, 1, 1)
  if (res.items.length > 0 && res.items[0].is_home) {
    // 注意：list 接口可能不返回完整的 config JSON 以节省流量
    // 如果后续需要完整配置，建议补齐 rpc_admin_get_diy_page_detail
    return res.items[0]
  }
  return null
}
