-- Fix the update trigger to only update updated_at when actual content changes
-- This prevents false "new submission" detection in the moderation queue

-- Drop and recreate the trigger function to add proper change detection
DROP TRIGGER IF EXISTS update_content_submissions_updated_at ON public.content_submissions;
DROP FUNCTION IF EXISTS public.update_content_submissions_updated_at();

CREATE OR REPLACE FUNCTION public.update_content_submissions_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  -- Only update updated_at if actual content has changed
  -- Ignore changes to: updated_at, assigned_to, assigned_at, locked_until, priority
  IF (
    NEW.content IS DISTINCT FROM OLD.content OR
    NEW.status IS DISTINCT FROM OLD.status OR
    NEW.reviewer_id IS DISTINCT FROM OLD.reviewer_id OR
    NEW.reviewer_notes IS DISTINCT FROM OLD.reviewer_notes OR
    NEW.escalated IS DISTINCT FROM OLD.escalated OR
    NEW.escalation_reason IS DISTINCT FROM OLD.escalation_reason OR
    NEW.approval_mode IS DISTINCT FROM OLD.approval_mode
  ) THEN
    NEW.updated_at = NOW();
  END IF;
  
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_content_submissions_updated_at
  BEFORE UPDATE ON public.content_submissions
  FOR EACH ROW
  EXECUTE FUNCTION public.update_content_submissions_updated_at();