-- =====================================================================================
-- RLS Policy: 优惠券模板表权限控制
-- 位置：docs/sql/20_rls/marketing/ml_coupon_templates_rls_v1.sql
-- 说明：确保商家仅能管理自己的优惠券模板，管理员拥有全权限。
-- =====================================================================================

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

-- 2. 创建权限策略
-- 允许商家管理自己的模板
CREATE POLICY ml_coupon_templates_merchant_policy ON public.ml_coupon_templates
    FOR ALL 
    TO authenticated
    USING (
        merchant_id = auth.uid() OR 
        EXISTS (
            SELECT 1 FROM public.ak_users 
            WHERE id = auth.uid() AND role = 'admin'
        )
    )
    WITH CHECK (
        merchant_id = auth.uid() OR 
        EXISTS (
            SELECT 1 FROM public.ak_users 
            WHERE id = auth.uid() AND role = 'admin'
        )
    );

-- 允许所有认证用户查看模板（用于前台领取）
CREATE POLICY ml_coupon_templates_select_policy ON public.ml_coupon_templates
    FOR SELECT 
    TO authenticated
    USING (status = 1);
