DROP POLICY IF EXISTS "Authenticated users can submit client requests" ON public.client_requests;
DROP POLICY IF EXISTS "Users can view their own submitted requests" ON public.client_requests;
DROP POLICY IF EXISTS "Staff full access on client_requests" ON public.client_requests;

CREATE POLICY "Association users can submit client requests"
ON public.client_requests
FOR INSERT
TO authenticated
WITH CHECK (
  public.user_belongs_to_association(auth.uid(), association_id)
  OR public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
);

CREATE POLICY "Board members can view association client requests"
ON public.client_requests
FOR SELECT
TO authenticated
USING (
  association_id IN (
    SELECT bm.association_id
    FROM public.board_members bm
    WHERE bm.user_id = auth.uid()
  )
);

CREATE POLICY "Users can view their own submitted client requests"
ON public.client_requests
FOR SELECT
TO authenticated
USING (
  requester_email = (
    SELECT au.email::text
    FROM auth.users au
    WHERE au.id = auth.uid()
  )
  AND public.user_belongs_to_association(auth.uid(), association_id)
);

CREATE POLICY "Staff full access on client_requests"
ON public.client_requests
FOR ALL
TO authenticated
USING (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
)
WITH CHECK (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
);

DROP POLICY IF EXISTS "Staff full access on calendar_events" ON public.calendar_events;
CREATE POLICY "Staff full access on calendar_events"
ON public.calendar_events
FOR ALL
TO authenticated
USING (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
)
WITH CHECK (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
);

DROP POLICY IF EXISTS "Staff full access on blocked_dates" ON public.blocked_dates;
CREATE POLICY "Staff full access on blocked_dates"
ON public.blocked_dates
FOR ALL
TO authenticated
USING (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
)
WITH CHECK (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
);