import supa, { ensureSupabaseReady } from '@/components/supadb/aksupainstance.uts'

export async function rpcOrEmptyArray(functionName: string, params: UTSJSONObject): Promise<Array<UTSJSONObject>> {
  await ensureSupabaseReady()
  const res: any = await supa.rpc(functionName, params)
  if (res?.status === 404) {
    return [] as Array<UTSJSONObject>
  }
  if (res?.error != null) {
    throw res.error
  }
  const anyData = res.data as any
  return Array.isArray(anyData) ? (anyData as Array<UTSJSONObject>) : ([] as Array<UTSJSONObject>)
}

export async function rpcOrNull(functionName: string, params: UTSJSONObject): Promise<UTSJSONObject | null> {
  await ensureSupabaseReady()
  const res: any = await supa.rpc(functionName, params)
  if (res?.status === 404) {
    return null
  }
  if (res?.error != null) {
    throw res.error
  }
  const anyData = res.data as any
  if (Array.isArray(anyData)) {
    return anyData.length > 0 ? (anyData[0] as UTSJSONObject) : null
  }
  return anyData != null ? (anyData as UTSJSONObject) : null
}

export async function rpcOrValue(functionName: string, params: UTSJSONObject): Promise<any> {
  await ensureSupabaseReady()
  const res: any = await supa.rpc(functionName, params)
  if (res?.status === 404) {
    return null
  }
  if (res?.error != null) {
    throw res.error
  }
  return res.data
}
