-- =====================================================================================
-- Schema: 签到规则配置表
-- 位置：docs/sql/10_schema/marketing/ak_signin_configs_v1.sql
-- 说明：记录每日签到积分、连续签到奖励及规则说明，按商家隔离。
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ak_signin_configs (
    id TEXT PRIMARY KEY DEFAULT 'signin_config', -- 每个商家一个配置记录
    merchant_id UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    
    is_enabled BOOLEAN DEFAULT true,             -- 签到功能是否启用
    daily_points INTEGER DEFAULT 10,             -- 每日签到固定奖励积分
    
    -- 连续签到奖励 (JSONB 格式): [{ "day": 3, "points": 20 }, { "day": 7, "points": 50 }]
    continuous_rewards JSONB DEFAULT '[]'::jsonb, 
    
    rules_description TEXT DEFAULT '1.每日签到可获得积分奖励；\n2.连续签到满足天数可获得额外阶梯奖励；\n3.签到中断将重新从第一天开始计算。',
    
    updated_at TIMESTAMPTZ DEFAULT now(),
    updated_by UUID REFERENCES auth.users(id),

    -- 约束：同一个商家只有一个签到配置记录
    UNIQUE(merchant_id)
);

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

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

-- 允许所有认证用户查看配置（用于移动端签到展示）
CREATE POLICY "Authenticated users can view signin configs"
ON public.ak_signin_configs
FOR SELECT
TO authenticated
USING (true);
