-- =====================================================================================
-- Schema: 直播商品管理表
-- 位置：docs/sql/10_schema/marketing/ak_live_products_v1.sql
-- 说明：管理直播活动关联的商品，支持直播价设置与审核状态，按商家隔离。
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ak_marketing_live_products (
    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,
    
    live_price DECIMAL(12,2) NOT NULL DEFAULT 0,  -- 直播专属价
    stock INTEGER DEFAULT 0,                     -- 直播可用库存
    
    audit_status INTEGER DEFAULT 1,              -- 审核状态: 1待审核, 2审核通过, 3审核驳回
    is_show BOOLEAN DEFAULT true,                -- 是否在直播间显示
    
    sort_order INTEGER DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

-- 启用 RLS
ALTER TABLE public.ak_marketing_live_products ENABLE ROW LEVEL SECURITY;

-- 权限策略：商家仅能管理自己的直播商品
CREATE POLICY "Merchants can manage their own live products"
ON public.ak_marketing_live_products FOR ALL 
TO authenticated
USING (merchant_id = auth.uid())
WITH CHECK (merchant_id = auth.uid());

-- 允许查看审核通过的商品
CREATE POLICY "Anyone can view approved live products"
ON public.ak_marketing_live_products FOR SELECT 
TO authenticated
USING (audit_status = 2 AND is_show = true);

-- 索引
CREATE INDEX IF NOT EXISTS idx_live_products_merchant ON public.ak_marketing_live_products(merchant_id);
CREATE INDEX IF NOT EXISTS idx_live_products_product ON public.ak_marketing_live_products(product_id);
