-- Allow recording votes for off-system members (name only, no auth user)
ALTER TABLE public.entity_votes ALTER COLUMN user_id DROP NOT NULL;
ALTER TABLE public.entity_votes ADD COLUMN IF NOT EXISTS voter_name text;
ALTER TABLE public.entity_votes ADD COLUMN IF NOT EXISTS recorded_by uuid REFERENCES auth.users(id) ON DELETE SET NULL;

-- Ensure either user_id or voter_name is present
ALTER TABLE public.entity_votes DROP CONSTRAINT IF EXISTS entity_votes_voter_present;
ALTER TABLE public.entity_votes ADD CONSTRAINT entity_votes_voter_present
  CHECK (user_id IS NOT NULL OR (voter_name IS NOT NULL AND length(btrim(voter_name)) > 0));

-- Prevent duplicate name-only votes per entity
CREATE UNIQUE INDEX IF NOT EXISTS entity_votes_name_only_unique
  ON public.entity_votes (entity_type, entity_id, lower(btrim(voter_name)))
  WHERE user_id IS NULL;
