-- Drop the existing policy if it exists
DROP POLICY IF EXISTS "Allow SUUID searches" ON public.users;

-- Create a new policy to explicitly allow SUUID searches
CREATE POLICY "Allow SUUID searches - Exact Match" ON public.users
FOR SELECT
USING (
    suuid = current_setting('request.jwt.claims')::json ->> 'search_term'
    OR indexable = true
);

-- Create an alternative approach: more permissive policy for SUUID searches
CREATE POLICY "Allow SUUID searches - Permissive" ON public.users
FOR SELECT
USING (
    suuid = ANY (
        ARRAY (
            SELECT
                unnest(
                    regexp_split_to_array(
                        current_setting('request.jwt.claims')::json ->> 'search_term',
                        ','
                    )
                )
        )
    )
    OR indexable = true
);

-- Create or replace the search_users function
CREATE OR REPLACE FUNCTION public.search_users (search_term TEXT) 
RETURNS TABLE (
    uuid UUID,
    suuid TEXT,
    username TEXT,
    indexable BOOLEAN
) AS $$
BEGIN
    -- Set the search term in the current transaction
    SET LOCAL "request.jwt.claim.search_term" = search_term;
    
    RETURN QUERY
    SELECT 
        u.uuid,
        u.suuid::TEXT,
        CASE 
            WHEN u.suuid = search_term OR u.indexable THEN u.username
            ELSE NULL 
        END,
        u.indexable
    FROM public.users u
    WHERE 
        u.suuid = search_term
        OR (
            u.indexable = true AND
            u.username ILIKE '%' || search_term || '%'
        );
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
