CREATE TABLE public.board_vote_responses (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  board_vote_id UUID NOT NULL REFERENCES public.board_votes(id) ON DELETE CASCADE,
  user_id UUID NOT NULL,
  vote_option TEXT NOT NULL,
  recorded_by UUID,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  UNIQUE (board_vote_id, user_id)
);

ALTER TABLE public.board_vote_responses ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Authenticated users can view vote responses"
ON public.board_vote_responses FOR SELECT
TO authenticated
USING (true);

CREATE POLICY "Authenticated users can insert their own vote"
ON public.board_vote_responses FOR INSERT
TO authenticated
WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Admins can insert votes on behalf of others"
ON public.board_vote_responses FOR INSERT
TO authenticated
WITH CHECK (public.has_role(auth.uid(), 'admin') OR public.has_role(auth.uid(), 'manager'));

CREATE TRIGGER update_board_vote_responses_updated_at
BEFORE UPDATE ON public.board_vote_responses
FOR EACH ROW
EXECUTE FUNCTION public.update_updated_at_column();