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

export type AdminUserGroup = {
  id: string
  name: string
  remark: string | null
  status: number
  created_at: string | null
  updated_at: string | null
  deleted_at: string | null
}

export type AdminUserGroupPageResult = {
  total: number
  items: Array<AdminUserGroup>
}

export type AdminUserGroupPageFilters = {
  search?: string | null
  status?: number | null
  includeDeleted?: boolean
}

/**
 * 分页获取用户分组列表
 */
export async function fetchAdminUserGroupPage(
  page: number,
  pageSize: number,
  filters: AdminUserGroupPageFilters = {}
): Promise<AdminUserGroupPageResult> {
  const res = await rpcOrNull('rpc_admin_user_group_list', {
    p_page: page,
    p_page_size: pageSize,
    p_search: filters.search ?? null,
    p_status: filters.status ?? null,
    p_include_deleted: filters.includeDeleted ?? false
  } as any)

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

  const anyTotal = (res as any).total
  const anyItems = (res as any).items

  const total = typeof anyTotal === 'number' ? anyTotal : parseInt(String(anyTotal ?? '0'))
  const items = Array.isArray(anyItems) ? (anyItems as Array<any>) : ([] as Array<any>)

  return { total, items: items as Array<AdminUserGroup> }
}

export type SaveAdminUserGroupInput = {
  id?: string | null
  name: string
  remark?: string | null
  status?: number
}

/**
 * 保存/更新用户分组
 */
export async function saveAdminUserGroup(input: SaveAdminUserGroupInput): Promise<string | null> {
  const res = await rpcOrValue('rpc_admin_user_group_save', {
    p_id: input.id ?? null,
    p_name: input.name,
    p_remark: input.remark ?? null,
    p_status: input.status ?? 1
  } as any)

  return res != null ? String(res) : null
}

/**
 * 逻辑删除用户分组
 */
export async function deleteAdminUserGroup(id: string): Promise<boolean> {
  const ok = await rpcOrValue('rpc_admin_user_group_delete', {
    p_id: id
  } as any)
  return ok === true
}

/**
 * 设置用户分组状态
 */
export async function setAdminUserGroupStatus(id: string, status: number): Promise<boolean> {
  const ok = await rpcOrValue('rpc_admin_user_group_set_status', {
    p_id: id,
    p_status: status
  } as any)
  return ok === true
}
