
-- Board members: insert documents for their assigned associations
CREATE POLICY "Board members can insert association documents"
ON public.documents
FOR INSERT
TO authenticated
WITH CHECK (
  association_id IN (
    SELECT bm.association_id FROM public.board_members bm WHERE bm.user_id = auth.uid()
  )
);

-- Board members: update documents for their assigned associations
CREATE POLICY "Board members can update association documents"
ON public.documents
FOR UPDATE
TO authenticated
USING (
  association_id IN (
    SELECT bm.association_id FROM public.board_members bm WHERE bm.user_id = auth.uid()
  )
)
WITH CHECK (
  association_id IN (
    SELECT bm.association_id FROM public.board_members bm WHERE bm.user_id = auth.uid()
  )
);

-- Board members: delete documents for their assigned associations
CREATE POLICY "Board members can delete association documents"
ON public.documents
FOR DELETE
TO authenticated
USING (
  association_id IN (
    SELECT bm.association_id FROM public.board_members bm WHERE bm.user_id = auth.uid()
  )
);

-- Storage: allow board members to upload to the files bucket under their association folder
-- Path convention used by the app: "<association_id>/<folder>/<filename>"
CREATE POLICY "Board members can upload association files"
ON storage.objects
FOR INSERT
TO authenticated
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()
    )
  )
);

CREATE POLICY "Board members can update association files"
ON storage.objects
FOR UPDATE
TO authenticated
USING (
  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()
    )
  )
)
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()
    )
  )
);

CREATE POLICY "Board members can delete association files"
ON storage.objects
FOR DELETE
TO authenticated
USING (
  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()
    )
  )
);
