CREATE TABLE public.mailchimp_configs (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  association_id UUID NOT NULL UNIQUE REFERENCES public.associations(id) ON DELETE CASCADE,
  api_key TEXT NOT NULL,
  server_prefix TEXT NOT NULL,
  audience_id TEXT,
  audience_name TEXT,
  last_sync_at TIMESTAMP WITH TIME ZONE,
  last_sync_status TEXT,
  last_sync_count INTEGER DEFAULT 0,
  last_sync_error TEXT,
  created_by UUID,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

ALTER TABLE public.mailchimp_configs ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Staff can view mailchimp configs"
ON public.mailchimp_configs FOR SELECT
USING (public.has_role(auth.uid(), 'admin'::public.app_role) OR public.has_role(auth.uid(), 'manager'::public.app_role));

CREATE POLICY "Staff can insert mailchimp configs"
ON public.mailchimp_configs FOR INSERT
WITH CHECK (public.has_role(auth.uid(), 'admin'::public.app_role) OR public.has_role(auth.uid(), 'manager'::public.app_role));

CREATE POLICY "Staff can update mailchimp configs"
ON public.mailchimp_configs FOR UPDATE
USING (public.has_role(auth.uid(), 'admin'::public.app_role) OR public.has_role(auth.uid(), 'manager'::public.app_role));

CREATE POLICY "Staff can delete mailchimp configs"
ON public.mailchimp_configs FOR DELETE
USING (public.has_role(auth.uid(), 'admin'::public.app_role) OR public.has_role(auth.uid(), 'manager'::public.app_role));

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