-- Recreate get_my_sessions as STABLE for PostgREST compatibility
-- PostgREST requires STABLE or IMMUTABLE volatility for RPC endpoints

-- Drop existing VOLATILE function
DROP FUNCTION IF EXISTS public.get_my_sessions();

-- Recreate as STABLE (doesn't modify data, results consistent within transaction)
CREATE OR REPLACE FUNCTION public.get_my_sessions()
RETURNS TABLE (
  id uuid,
  created_at timestamptz,
  updated_at timestamptz,
  refreshed_at timestamp,
  user_agent text,
  ip text,
  not_after timestamptz,
  aal text
)
LANGUAGE plpgsql
SECURITY DEFINER
STABLE  -- KEY CHANGE: STABLE instead of VOLATILE for PostgREST
SET search_path = auth, public
AS $$
BEGIN
  RETURN QUERY
  SELECT 
    s.id,
    s.created_at,
    s.updated_at,
    s.refreshed_at,
    s.user_agent,
    public.hash_session_ip(s.ip) as ip,
    s.not_after,
    s.aal::text
  FROM auth.sessions s
  WHERE s.user_id = auth.uid()
  ORDER BY s.refreshed_at DESC NULLS LAST;
END;
$$;

-- Grant explicit permissions (PostgREST requires both roles)
GRANT EXECUTE ON FUNCTION public.get_my_sessions() TO authenticated;
GRANT EXECUTE ON FUNCTION public.get_my_sessions() TO anon;

-- Add comment for PostgREST OpenAPI documentation
COMMENT ON FUNCTION public.get_my_sessions() IS 'Returns current user''s active sessions with hashed IP addresses for security. Requires authentication.';