-- Chapters: timestamped sections within a podcast episode
CREATE TABLE public.chapters (
  id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
  podcast_id uuid REFERENCES public.podcasts(id) ON DELETE CASCADE NOT NULL,
  title text NOT NULL,
  start_time_seconds integer NOT NULL DEFAULT 0,
  sort_order integer NOT NULL DEFAULT 0,
  created_at timestamptz DEFAULT now()
);

CREATE INDEX idx_chapters_podcast ON public.chapters(podcast_id);

ALTER TABLE public.chapters ENABLE ROW LEVEL SECURITY;

-- Everyone can read chapters
CREATE POLICY "chapters_read" ON public.chapters
  FOR SELECT USING (true);

-- Only the podcast creator can manage chapters
CREATE POLICY "chapters_insert" ON public.chapters
  FOR INSERT WITH CHECK (
    podcast_id IN (SELECT id FROM public.podcasts WHERE creator_id = auth.uid())
  );

CREATE POLICY "chapters_update" ON public.chapters
  FOR UPDATE USING (
    podcast_id IN (SELECT id FROM public.podcasts WHERE creator_id = auth.uid())
  );

CREATE POLICY "chapters_delete" ON public.chapters
  FOR DELETE USING (
    podcast_id IN (SELECT id FROM public.podcasts WHERE creator_id = auth.uid())
  );
