-- =====================================================================================
-- Schema: 砍价与团购活动表
-- 位置：docs/sql/10_schema/marketing/ak_bargain_groupbuy_v1.sql
-- 说明：管理砍价与团购活动，按商家隔离。
-- =====================================================================================

-- 1. 砍价活动表
CREATE TABLE IF NOT EXISTS public.ak_marketing_bargains (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    merchant_id UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    product_id UUID NOT NULL REFERENCES public.ml_products(id) ON DELETE CASCADE,
    
    title TEXT NOT NULL,                         -- 活动标题
    min_price DECIMAL(12,2) NOT NULL DEFAULT 0,  -- 砍价最低价
    stock INTEGER DEFAULT 0,                     -- 活动库存
    
    start_time TIMESTAMPTZ NOT NULL,             -- 开始时间
    stop_time 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_marketing_groupbuys (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    merchant_id UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    product_id UUID NOT NULL REFERENCES public.ml_products(id) ON DELETE CASCADE,
    
    title TEXT NOT NULL,                         -- 活动标题
    price DECIMAL(12,2) NOT NULL DEFAULT 0,      -- 团购价格
    people INTEGER DEFAULT 2,                    -- 成团人数要求
    stock INTEGER DEFAULT 0,                     -- 活动库存
    
    start_time TIMESTAMPTZ NOT NULL,             -- 开始时间
    stop_time TIMESTAMPTZ NOT NULL,              -- 结束时间
    
    status BOOLEAN DEFAULT true,                 -- 状态: true开启, false关闭
    
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

-- 3. 启用 RLS
ALTER TABLE public.ak_marketing_bargains ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ak_marketing_groupbuys ENABLE ROW LEVEL SECURITY;

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

-- 团购策略
CREATE POLICY "Merchants can manage their own groupbuys"
ON public.ak_marketing_groupbuys 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_marketing_bargains FOR SELECT 
TO authenticated
USING (status = true);

CREATE POLICY "Anyone can view active groupbuys"
ON public.ak_marketing_groupbuys FOR SELECT 
TO authenticated
USING (status = true);

-- 5. 索引
CREATE INDEX IF NOT EXISTS idx_bargains_merchant ON public.ak_marketing_bargains(merchant_id);
CREATE INDEX IF NOT EXISTS idx_groupbuys_merchant ON public.ak_marketing_groupbuys(merchant_id);
