-- =====================================================
-- Optimistic Locking via Version Column
--
-- Problem: Two admins editing the same member silently
-- overwrite each other's changes. Last write wins.
--
-- Fix: Add version column, auto-increment on update.
-- API layer checks version match before writing.
-- =====================================================

-- Add version column
ALTER TABLE public.members
  ADD COLUMN IF NOT EXISTS version integer NOT NULL DEFAULT 1;

-- Auto-increment version on every update
CREATE OR REPLACE FUNCTION public.increment_member_version()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
BEGIN
  NEW.version := OLD.version + 1;
  RETURN NEW;
END;
$$;

CREATE TRIGGER trg_members_increment_version
  BEFORE UPDATE ON public.members
  FOR EACH ROW
  EXECUTE FUNCTION public.increment_member_version();
