-- =====================================================================================
-- Schema: 签到记录表
-- 位置：docs/sql/10_schema/marketing/ak_marketing_signin_logs_v1.sql
-- 说明：记录用户每日签到的详细流水，按商家隔离。
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ak_marketing_signin_logs (
    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) ON DELETE CASCADE,
    
    points INTEGER NOT NULL DEFAULT 0,            -- 本次签到获得的积分
    is_continuous_reward BOOLEAN DEFAULT false,   -- 是否包含连续签到额外奖励
    
    created_at TIMESTAMPTZ DEFAULT now()
);

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

-- 权限策略：商家仅能管理/查看自己的签到记录
CREATE POLICY "Merchants manage their own signin logs"
ON public.ak_marketing_signin_logs FOR ALL 
TO authenticated
USING (merchant_id = auth.uid())
WITH CHECK (merchant_id = auth.uid());

-- 允许用户查看自己的签到记录
CREATE POLICY "Users view own signin logs"
ON public.ak_marketing_signin_logs FOR SELECT 
TO authenticated
USING (uid = auth.uid());

-- 索引
CREATE INDEX IF NOT EXISTS idx_signin_logs_merchant ON public.ak_marketing_signin_logs(merchant_id);
CREATE INDEX IF NOT EXISTS idx_signin_logs_uid ON public.ak_marketing_signin_logs(uid, created_at DESC);
