-- Templates: replace narrow staff policy with broader staff role coverage
DROP POLICY IF EXISTS "Staff can manage form templates" ON public.public_form_templates;

CREATE POLICY "Staff can manage form templates"
ON public.public_form_templates
FOR ALL
TO authenticated
USING (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'staff'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
  OR public.has_role(auth.uid(), 'management'::public.app_role)
  OR public.has_role(auth.uid(), 'association_management'::public.app_role)
)
WITH CHECK (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'staff'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
  OR public.has_role(auth.uid(), 'management'::public.app_role)
  OR public.has_role(auth.uid(), 'association_management'::public.app_role)
);

-- Submissions: ensure anon insert is tight and staff have full management
DROP POLICY IF EXISTS "Anon can submit forms for valid template" ON public.public_form_submissions;
DROP POLICY IF EXISTS "Staff can manage form submissions" ON public.public_form_submissions;

CREATE POLICY "Anyone can submit to published forms"
ON public.public_form_submissions
FOR INSERT
TO anon, authenticated
WITH CHECK (
  EXISTS (
    SELECT 1 FROM public.public_form_templates t
    WHERE t.id = public_form_submissions.template_id
      AND t.association_id = public_form_submissions.association_id
      AND t.is_published = true
  )
);

CREATE POLICY "Staff can manage form submissions"
ON public.public_form_submissions
FOR ALL
TO authenticated
USING (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'staff'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
  OR public.has_role(auth.uid(), 'management'::public.app_role)
  OR public.has_role(auth.uid(), 'association_management'::public.app_role)
)
WITH CHECK (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
  OR public.has_role(auth.uid(), 'staff'::public.app_role)
  OR public.has_role(auth.uid(), 'employee'::public.app_role)
  OR public.has_role(auth.uid(), 'management'::public.app_role)
  OR public.has_role(auth.uid(), 'association_management'::public.app_role)
);