
-- 1. Fix forte_account_mappings: replace blanket SELECT with association-scoped
DROP POLICY IF EXISTS "Authenticated users can view forte mappings" ON public.forte_account_mappings;

CREATE POLICY "Users can view own association forte mappings"
  ON public.forte_account_mappings
  FOR SELECT TO authenticated
  USING (
    is_active = true
    AND (
      has_role(auth.uid(), 'admin'::app_role)
      OR has_role(auth.uid(), 'manager'::app_role)
      OR association_id IN (SELECT get_user_association_ids())
    )
  );

-- 2. Fix election_ballots: replace blanket anon SELECT with token-scoped
DROP POLICY IF EXISTS "Anon can select own ballots" ON public.election_ballots;

CREATE POLICY "Anon can select ballots by vote_token"
  ON public.election_ballots
  FOR SELECT TO anon
  USING (
    vote_token IN (
      SELECT ev.vote_token FROM public.election_eligible_voters ev
      WHERE ev.vote_token = election_ballots.vote_token
    )
  );

CREATE POLICY "Authenticated users can select own ballots"
  ON public.election_ballots
  FOR SELECT TO authenticated
  USING (
    vote_token IN (
      SELECT ev.vote_token FROM public.election_eligible_voters ev
      WHERE ev.owner_id IN (
        SELECT o.id FROM public.owners o WHERE o.user_id = auth.uid()
      )
    )
    OR has_role(auth.uid(), 'admin'::app_role)
    OR has_role(auth.uid(), 'manager'::app_role)
  );

-- 3. Fix arc_applications: drop blanket SELECT (scoped policies already exist)
DROP POLICY IF EXISTS "Authenticated users can view arc_applications" ON public.arc_applications;
