-- Fix search_path security vulnerability in update_content_submissions_updated_at
-- This addresses the function_search_path_mutable linter warning

DROP FUNCTION IF EXISTS public.update_content_submissions_updated_at() CASCADE;

CREATE OR REPLACE FUNCTION public.update_content_submissions_updated_at()
RETURNS TRIGGER 
LANGUAGE plpgsql
SET search_path = 'public'
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.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;
$$;

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

COMMENT ON FUNCTION public.update_content_submissions_updated_at() IS 
  'SECURITY HARDENED: Trigger function to update updated_at timestamp only when meaningful fields change. Includes SET search_path to prevent search path injection attacks.';