-- Fix RLS: use auth.email() instead of querying auth.users
DROP POLICY IF EXISTS "Recipients view their envelopes" ON public.signature_envelopes;
DROP POLICY IF EXISTS "Recipients view themselves" ON public.signature_recipients;

CREATE POLICY "Recipients view their envelopes"
ON public.signature_envelopes
FOR SELECT
USING (
  EXISTS (
    SELECT 1 FROM public.signature_recipients r
    WHERE r.envelope_id = signature_envelopes.id
      AND (r.user_id = auth.uid() OR lower(r.email) = lower(auth.email()))
  )
);

CREATE POLICY "Recipients view themselves"
ON public.signature_recipients
FOR SELECT
USING (
  user_id = auth.uid() OR lower(email) = lower(auth.email())
);