-- =====================================================================================
-- Schema: 秒杀与拼团活动表
-- 位置：docs/sql/10_schema/marketing/ak_advanced_marketing_v1.sql
-- 说明：管理秒杀活动与拼团活动，按商家隔离。
-- =====================================================================================

-- 1. 秒杀活动表
CREATE TABLE IF NOT EXISTS public.ak_seckill_activities (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    merchant_id UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    
    title TEXT NOT NULL,                         -- 活动标题
    single_limit INTEGER DEFAULT 1,              -- 单次限购
    total_limit INTEGER DEFAULT 10,              -- 总购买数量限制
    product_count INTEGER DEFAULT 0,             -- 包含商品数量
    time_range TEXT NOT NULL,                    -- 活动时段 (如 "06:00-24:00")
    
    start_date TIMESTAMPTZ NOT NULL,             -- 开始日期
    end_date TIMESTAMPTZ NOT NULL,               -- 结束日期
    
    status BOOLEAN DEFAULT true,                 -- 状态: true开启, false关闭
    
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

-- 2. 拼团活动表 (开团记录)
CREATE TABLE IF NOT EXISTS public.ak_combination_activities (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    merchant_id UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    
    uid UUID NOT NULL REFERENCES public.ak_users(id), -- 开团团长
    product_id UUID NOT NULL REFERENCES public.ml_products(id), -- 拼团商品
    
    people INTEGER DEFAULT 2,                    -- 几人团
    count_people INTEGER DEFAULT 1,              -- 当前几人参加
    
    start_time TIMESTAMPTZ DEFAULT now(),        -- 开团时间
    stop_time TIMESTAMPTZ NOT NULL,              -- 结束时间
    
    status TEXT NOT NULL DEFAULT 'ongoing',      -- ongoing进行中, pending未完成, ended已成功
    
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now(),

    CONSTRAINT chk_comb_status CHECK (status IN ('ongoing', 'pending', 'ended'))
);

-- 3. 启用 RLS
ALTER TABLE public.ak_seckill_activities ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ak_combination_activities ENABLE ROW LEVEL SECURITY;

-- 4. 创建权限策略 (按 merchant_id 隔离)
-- 秒杀策略
CREATE POLICY "Merchants can manage their own seckill activities"
ON public.ak_seckill_activities FOR ALL 
TO authenticated
USING (merchant_id = auth.uid())
WITH CHECK (merchant_id = auth.uid());

-- 拼团策略
CREATE POLICY "Merchants can manage their own combination activities"
ON public.ak_combination_activities FOR ALL 
TO authenticated
USING (merchant_id = auth.uid())
WITH CHECK (merchant_id = auth.uid());

-- 允许所有认证用户查看（用于移动端展示）
CREATE POLICY "Anyone can view active marketing activities"
ON public.ak_seckill_activities FOR SELECT 
TO authenticated
USING (status = true);

CREATE POLICY "Anyone can view ongoing combinations"
ON public.ak_combination_activities FOR SELECT 
TO authenticated
USING (true);
