-- Comprehensive RLS policies for entity_timeline_events

-- Drop existing policies if any
DROP POLICY IF EXISTS "Public can view public timeline events" ON public.entity_timeline_events;
DROP POLICY IF EXISTS "Service role can manage timeline events" ON public.entity_timeline_events;
DROP POLICY IF EXISTS "Users can view their own timeline submissions" ON public.entity_timeline_events;

-- Users can create timeline submissions (goes through moderation)
CREATE POLICY "Users can submit timeline events"
ON public.entity_timeline_events
FOR INSERT
TO authenticated
WITH CHECK (
  created_by = auth.uid() AND 
  approved_by IS NULL AND
  submission_id IS NOT NULL
);

-- Users can view their own pending submissions
CREATE POLICY "Users can view own pending timeline events"
ON public.entity_timeline_events
FOR SELECT
TO authenticated
USING (
  created_by = auth.uid() AND 
  approved_by IS NULL
);

-- Users can update their own pending submissions
CREATE POLICY "Users can update own pending timeline events"
ON public.entity_timeline_events
FOR UPDATE
TO authenticated
USING (
  created_by = auth.uid() AND 
  approved_by IS NULL
)
WITH CHECK (
  created_by = auth.uid() AND 
  approved_by IS NULL
);

-- Users can delete their own pending submissions only
CREATE POLICY "Users can delete own pending timeline events"
ON public.entity_timeline_events
FOR DELETE
TO authenticated
USING (
  created_by = auth.uid() AND 
  approved_by IS NULL
);

-- Public can view approved timeline events
CREATE POLICY "Public can view approved timeline events"
ON public.entity_timeline_events
FOR SELECT
USING (
  is_public = true AND 
  approved_by IS NOT NULL
);

-- Moderators can view all timeline events
CREATE POLICY "Moderators can view all timeline events"
ON public.entity_timeline_events
FOR SELECT
TO authenticated
USING (is_moderator(auth.uid()));

-- Moderators can manage all timeline events with MFA
CREATE POLICY "Moderators can update timeline events"
ON public.entity_timeline_events
FOR UPDATE
TO authenticated
USING (is_moderator(auth.uid()) AND has_aal2())
WITH CHECK (is_moderator(auth.uid()) AND has_aal2());

CREATE POLICY "Moderators can delete timeline events"
ON public.entity_timeline_events
FOR DELETE
TO authenticated
USING (is_moderator(auth.uid()) AND has_aal2());

-- Service role can manage all (for edge functions)
CREATE POLICY "Service role can manage timeline events"
ON public.entity_timeline_events
FOR ALL
TO service_role
USING (true)
WITH CHECK (true);