
CREATE TABLE public.saved_form_templates (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  form_type text NOT NULL,
  name text NOT NULL,
  association_id uuid REFERENCES public.associations(id) ON DELETE SET NULL,
  form_data jsonb NOT NULL DEFAULT '{}'::jsonb,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

ALTER TABLE public.saved_form_templates ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Staff full access on saved_form_templates"
ON public.saved_form_templates
FOR ALL
TO authenticated
USING (has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'manager'::app_role))
WITH CHECK (has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'manager'::app_role));

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