DROP FUNCTION update_user_requests(uuid,text[]);


-- Create function to update user requests

CREATE
OR REPLACE FUNCTION public.update_user_requests(

  search_term TEXT,

  new_request TEXT -- Single SUUID to add/remove

) RETURNS boolean AS $$

DECLARE

target_user_uuid UUID;

  current_requests
TEXT[];

BEGIN

  -- First, find the target user based on SUUID or username (if indexable)

SELECT uuid, requests
INTO target_user_uuid, current_requests

FROM public.users

WHERE suuid = search_term

   OR (
    username = search_term
        AND indexable = true
    )

    LIMIT 1;



IF
target_user_uuid IS NULL THEN

    RETURN false;

END IF;



  -- Update the requests array

  -- Add if not exists, remove if exists

  IF
new_request = ANY(current_requests) THEN

    -- Remove the request

UPDATE public.users

SET requests = array_remove(requests, new_request)

WHERE uuid = target_user_uuid;

ELSE

    -- Add the request

UPDATE public.users

SET requests = array_append(requests, new_request)

WHERE uuid = target_user_uuid;

END IF;



  RETURN
FOUND;

END;

$$
LANGUAGE plpgsql SECURITY DEFINER;



-- Grant access to authenticated users

GRANT EXECUTE ON FUNCTION public.update_user_requests TO authenticated;