-- Migration: Add conflict tracking to content_submissions

-- Add columns for optimistic locking
ALTER TABLE public.content_submissions 
ADD COLUMN IF NOT EXISTS last_modified_at TIMESTAMPTZ DEFAULT NOW(),
ADD COLUMN IF NOT EXISTS last_modified_by UUID REFERENCES auth.users(id);

-- Create function to update modification tracking
CREATE OR REPLACE FUNCTION public.update_content_submission_modified()
RETURNS TRIGGER AS $$
BEGIN
  NEW.last_modified_at = NOW();
  NEW.last_modified_by = auth.uid();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public;

-- Create trigger
DROP TRIGGER IF EXISTS trigger_update_submission_modified ON public.content_submissions;
CREATE TRIGGER trigger_update_submission_modified
  BEFORE UPDATE ON public.content_submissions
  FOR EACH ROW
  EXECUTE FUNCTION public.update_content_submission_modified();

-- Add indexes for performance
CREATE INDEX IF NOT EXISTS idx_content_submissions_last_modified 
  ON public.content_submissions(last_modified_at);

CREATE INDEX IF NOT EXISTS idx_content_submissions_last_modified_by 
  ON public.content_submissions(last_modified_by);