
CREATE TABLE public.docusign_envelopes (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  association_id UUID REFERENCES public.associations(id) NOT NULL,
  envelope_id TEXT,
  document_name TEXT NOT NULL,
  document_url TEXT,
  status TEXT NOT NULL DEFAULT 'created',
  recipients JSONB NOT NULL DEFAULT '[]'::jsonb,
  sent_by UUID REFERENCES auth.users(id),
  sent_at TIMESTAMPTZ,
  completed_at TIMESTAMPTZ,
  metadata JSONB DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE public.docusign_envelopes ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Staff can manage docusign envelopes"
  ON public.docusign_envelopes
  FOR ALL
  TO authenticated
  USING (
    public.has_role(auth.uid(), 'admin'::public.app_role) OR
    public.has_role(auth.uid(), 'manager'::public.app_role)
  )
  WITH CHECK (
    public.has_role(auth.uid(), 'admin'::public.app_role) OR
    public.has_role(auth.uid(), 'manager'::public.app_role)
  );

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