
CREATE TABLE public.association_public_pages (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  association_id UUID REFERENCES public.associations(id) ON DELETE CASCADE NOT NULL UNIQUE,
  slug TEXT NOT NULL UNIQUE,
  is_published BOOLEAN NOT NULL DEFAULT false,
  welcome_message TEXT,
  cover_image_url TEXT,
  accent_color TEXT DEFAULT '#2563EB',
  logo_width INTEGER DEFAULT 200,
  modules_enabled JSONB NOT NULL DEFAULT '{"calendar": false, "booking": false}'::jsonb,
  booking_config JSONB DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE public.association_public_pages ENABLE ROW LEVEL SECURITY;

-- Public read for published pages
CREATE POLICY "Anyone can view published public pages"
  ON public.association_public_pages
  FOR SELECT
  USING (is_published = true);

-- Staff can manage
CREATE POLICY "Staff can manage public pages"
  ON public.association_public_pages
  FOR ALL
  TO authenticated
  USING (
    EXISTS (
      SELECT 1 FROM public.user_roles
      WHERE user_id = auth.uid()
      AND role IN ('admin', 'manager', 'employee')
    )
  )
  WITH CHECK (
    EXISTS (
      SELECT 1 FROM public.user_roles
      WHERE user_id = auth.uid()
      AND role IN ('admin', 'manager', 'employee')
    )
  );

CREATE INDEX idx_association_public_pages_slug ON public.association_public_pages(slug);
