import { getUserSQL } from '@supabase/pg-meta' import { useQuery } from '@tanstack/react-query' import { authKeys } from './keys' import { User } from './users-infinite-query' import { executeSql } from '@/data/sql/execute-sql-mutation' import { UUID_REGEX } from '@/lib/constants' import { ResponseError, UseCustomQueryOptions } from '@/types' type UserVariables = { projectRef?: string connectionString?: string | null userId?: string | null } export async function getUser( { projectRef, connectionString, userId }: UserVariables, signal?: AbortSignal ) { if (!userId) throw new Error('UserID is required') if (!UUID_REGEX.test(userId)) throw new Error('Invalid user ID format') const sql = getUserSQL(userId) const { result } = await executeSql( { projectRef, connectionString, sql, queryKey: [`user-${userId}`] }, signal ) const user = result[0] as User | undefined return user } export type UserData = Awaited> export type UserError = ResponseError export const useUserQuery = ( { projectRef, connectionString, userId }: UserVariables, { enabled = true, ...options }: UseCustomQueryOptions = {} ) => useQuery({ queryKey: authKeys.user(projectRef, userId), queryFn: ({ signal }) => getUser({ projectRef, connectionString, userId }, signal), enabled: enabled && typeof projectRef !== 'undefined', ...options, })