-- Per-board-member "can upload" permission. When enabled, that board member may
-- upload association documents (files bucket + documents table) and create/manage
-- bids & quotes for their association(s). Default off.

alter table public.board_members
  add column if not exists can_upload boolean not null default false;

-- Documents: tighten the existing board insert policy to require the flag.
alter policy "Board members can insert association documents" on public.documents
  with check (
    association_id in (
      select bm.association_id from public.board_members bm
      where bm.user_id = auth.uid() and bm.can_upload
    )
  );

-- Storage (files bucket): same gate on the board upload policy.
alter policy "Board members can upload association files" on storage.objects
  with check (
    bucket_id = 'files'
    and ((storage.foldername(name))[1])::uuid in (
      select bm.association_id from public.board_members bm
      where bm.user_id = auth.uid() and bm.can_upload
    )
  );

-- Bids & Quotes: allow permitted board members to manage their association's bids.
drop policy if exists "Board members manage association bids" on public.bids_quotes;
create policy "Board members manage association bids" on public.bids_quotes
  for all
  using (
    association_id in (
      select bm.association_id from public.board_members bm
      where bm.user_id = auth.uid() and bm.can_upload
    )
  )
  with check (
    association_id in (
      select bm.association_id from public.board_members bm
      where bm.user_id = auth.uid() and bm.can_upload
    )
  );
