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

export type AdminCategory = {
  id: string
  name: string
  parent_id: string | null
  icon: string | null
  sort: number
  is_active: boolean
  level: number
  created_at: string
}

/**
 * 获取分类列表
 */
export async function fetchAdminCategoryList(filters: {
  name?: string,
  isActive?: boolean
}): Promise<Array<AdminCategory>> {
  const res = await rpcOrNull('rpc_admin_category_list', {
    p_name: filters.name ?? null,
    p_is_active: filters.isActive ?? null
  } as UTSJSONObject)

  if (res == null) return [] as Array<AdminCategory>
  
  const anyItems = (res as any).items
  return Array.isArray(anyItems) ? anyItems : [] as Array<AdminCategory>
}

/**
 * 创建分类
 */
export async function createAdminCategory(payload: {
  parentId?: string | null,
  name: string,
  slug?: string,
  description?: string,
  iconUrl?: string,
  bannerUrl?: string,
  sortOrder?: number,
  isActive?: boolean
}): Promise<string | null> {
  try {
    const id = await rpcOrValue('rpc_admin_category_create', {
      p_parent_id: payload.parentId ?? null,
      p_name: payload.name,
      p_slug: payload.slug ?? null,
      p_description: payload.description ?? null,
      p_icon_url: payload.iconUrl ?? null,
      p_banner_url: payload.bannerUrl ?? null,
      p_sort_order: payload.sortOrder ?? 0,
      p_is_active: payload.isActive ?? true
    } as UTSJSONObject)
    return typeof id === 'string' ? id as string : null
  } catch (e: any) {
    console.error('创建分类失败:', e)
    throw e
  }
}

/**
 * 更新分类
 */
export async function updateAdminCategory(payload: {
  id: string,
  parentId?: string | null,
  name: string,
  slug?: string,
  description?: string,
  iconUrl?: string,
  bannerUrl?: string,
  sortOrder?: number,
  isActive?: boolean
}): Promise<boolean> {
  try {
    const ok = await rpcOrValue('rpc_admin_category_update', {
      p_id: payload.id,
      p_parent_id: payload.parentId ?? null,
      p_name: payload.name,
      p_slug: payload.slug ?? null,
      p_description: payload.description ?? null,
      p_icon_url: payload.iconUrl ?? null,
      p_banner_url: payload.bannerUrl ?? null,
      p_sort_order: payload.sortOrder ?? 0,
      p_is_active: payload.isActive ?? true
    } as UTSJSONObject)
    return ok === true
  } catch (e: any) {
    console.error('更新分类失败:', e)
    throw e
  }
}

/**
 * 删除分类
 */
export async function deleteAdminCategory(id: string): Promise<boolean> {
  try {
    const ok = await rpcOrValue('rpc_admin_category_delete', {
      p_id: id
    } as UTSJSONObject)
    return ok === true
  } catch (e: any) {
    const error = e as UTSJSONObject
    const message = error.getString('message') ?? ''
    if (message.includes('子分类')) {
      throw new Error('请先删除该分类下的子分类')
    }
    if (message.includes('商品')) {
      throw new Error('该分类下仍有商品，无法删除')
    }
    throw e
  }
}
