-- Add RLS policies for system_alerts table

-- SELECT policy: Moderators can view system alerts
CREATE POLICY "Moderators can view system alerts"
ON public.system_alerts
FOR SELECT
TO authenticated
USING (
  EXISTS (
    SELECT 1 FROM public.user_roles
    WHERE user_id = auth.uid()
    AND role IN ('admin', 'moderator', 'superuser')
  )
);

-- INSERT policy: System can create alerts
CREATE POLICY "System can create alerts"
ON public.system_alerts
FOR INSERT
TO authenticated
WITH CHECK (true);

-- UPDATE policy: Moderators can resolve system alerts
CREATE POLICY "Moderators can resolve system alerts"
ON public.system_alerts
FOR UPDATE
TO authenticated
USING (
  EXISTS (
    SELECT 1 FROM public.user_roles
    WHERE user_id = auth.uid()
    AND role IN ('admin', 'moderator', 'superuser')
  )
)
WITH CHECK (
  EXISTS (
    SELECT 1 FROM public.user_roles
    WHERE user_id = auth.uid()
    AND role IN ('admin', 'moderator', 'superuser')
  )
);

-- Grant permissions to authenticated users
GRANT SELECT, INSERT, UPDATE ON public.system_alerts TO authenticated;