-- =====================================================================================
-- Schema: 新人礼配置表
-- 位置：docs/sql/10_schema/marketing/ak_marketing_newcomer_config_v1.sql
-- 说明：管理新用户注册后的奖励（余额、积分、优惠券），按商家隔离。
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ak_marketing_newcomer_config (
    id TEXT PRIMARY KEY DEFAULT 'newcomer_config',
    merchant_id UUID NOT NULL UNIQUE REFERENCES public.ak_users(id) ON DELETE CASCADE,
    
    balance_reward DECIMAL(12,2) DEFAULT 0.00,   -- 赠送余额
    integral_reward INTEGER DEFAULT 0,           -- 赠送积分
    
    -- 赠送优惠券 (JSONB 格式): [{ "id": "coupon_uuid", "name": "显示名称", "desc": "发放描述" }]
    coupons_json JSONB DEFAULT '[]'::jsonb, 
    
    updated_at TIMESTAMPTZ DEFAULT now(),
    updated_by UUID REFERENCES auth.users(id)
);

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

-- 权限策略：商家仅能管理自己的新人礼配置
CREATE POLICY "Merchants manage their own newcomer configs"
ON public.ak_marketing_newcomer_config FOR ALL 
TO authenticated
USING (merchant_id = auth.uid())
WITH CHECK (merchant_id = auth.uid());

-- 允许查看配置（用于移动端展示）
CREATE POLICY "Anyone can view newcomer config"
ON public.ak_marketing_newcomer_config FOR SELECT 
TO authenticated
USING (true);
