-- 知识付费平台数据表
-- 在 Supabase SQL Editor 中执行

-- 电子书专栏
CREATE TABLE IF NOT EXISTS wxgzh_ebooks (
  id BIGSERIAL PRIMARY KEY,
  title TEXT NOT NULL,
  cover TEXT,
  description TEXT,
  sort_order INT DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- 电子书章节
CREATE TABLE IF NOT EXISTS wxgzh_ebook_chapters (
  id BIGSERIAL PRIMARY KEY,
  ebook_id BIGINT NOT NULL REFERENCES wxgzh_ebooks(id) ON DELETE CASCADE,
  title TEXT NOT NULL,
  content TEXT,
  is_free BOOLEAN DEFAULT false,
  sort_order INT DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- 课程专栏
CREATE TABLE IF NOT EXISTS wxgzh_courses (
  id BIGSERIAL PRIMARY KEY,
  title TEXT NOT NULL,
  cover TEXT,
  description TEXT,
  sort_order INT DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- 课程章节（视频 + 配套文章）
CREATE TABLE IF NOT EXISTS wxgzh_course_chapters (
  id BIGSERIAL PRIMARY KEY,
  course_id BIGINT NOT NULL REFERENCES wxgzh_courses(id) ON DELETE CASCADE,
  title TEXT NOT NULL,
  video_url TEXT,
  article_markdown TEXT,
  duration INT DEFAULT 0,
  is_free BOOLEAN DEFAULT false,
  sort_order INT DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- 若表已存在，可单独执行添加列：
-- ALTER TABLE wxgzh_course_chapters ADD COLUMN IF NOT EXISTS article_markdown TEXT;

-- VIP 用户表（user_id 对应 auth.users.id）
CREATE TABLE IF NOT EXISTS wxgzh_vip_users (
  id BIGSERIAL PRIMARY KEY,
  user_id UUID NOT NULL UNIQUE REFERENCES auth.users(id) ON DELETE CASCADE,
  expire_at TIMESTAMPTZ NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- 启用 RLS
ALTER TABLE wxgzh_ebooks ENABLE ROW LEVEL SECURITY;
ALTER TABLE wxgzh_ebook_chapters ENABLE ROW LEVEL SECURITY;
ALTER TABLE wxgzh_courses ENABLE ROW LEVEL SECURITY;
ALTER TABLE wxgzh_course_chapters ENABLE ROW LEVEL SECURITY;
ALTER TABLE wxgzh_vip_users ENABLE ROW LEVEL SECURITY;

-- 公开读取策略（专栏和章节列表可匿名读）
CREATE POLICY "ebooks_public_read" ON wxgzh_ebooks FOR SELECT USING (true);
CREATE POLICY "ebook_chapters_public_read" ON wxgzh_ebook_chapters FOR SELECT USING (true);
CREATE POLICY "courses_public_read" ON wxgzh_courses FOR SELECT USING (true);
CREATE POLICY "course_chapters_public_read" ON wxgzh_course_chapters FOR SELECT USING (true);

-- VIP 表仅允许用户查询自己的记录
CREATE POLICY "vip_users_select_own" ON wxgzh_vip_users FOR SELECT USING (auth.uid() = user_id);

-- 示例数据可在 Supabase 后台手动插入，或使用 mock 数据（前端已内置）
