-- Fix the update trigger to preserve timestamps when only metadata changes
-- This prevents false "new submission" detection when priority is recalculated

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, review_count, first_reviewed_at, resolved_at, submitted_at
  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 OR
    NEW.user_id IS DISTINCT FROM OLD.user_id OR
    NEW.submission_type IS DISTINCT FROM OLD.submission_type OR
    NEW.escalated_by IS DISTINCT FROM OLD.escalated_by OR
    NEW.escalated_at IS DISTINCT FROM OLD.escalated_at OR
    NEW.original_submission_id IS DISTINCT FROM OLD.original_submission_id
  ) THEN
    NEW.updated_at = NOW();
  ELSE
    -- Keep the old updated_at timestamp if only metadata changed
    NEW.updated_at = OLD.updated_at;
  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();