-- =====================================================================================
-- RLS: 分销模块安全策略
-- 位置：docs/sql/20_rls/distribution/ml_distribution_rls_v1.sql
-- 对象类型：RLS 策略
-- 版本：v1
-- 说明：管理端全量权限通过 SECURITY DEFINER RPC 执行；用户仅能访问个人关联数据
-- =====================================================================================

-- 启用 RLS
ALTER TABLE public.ak_distribution_config ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ak_distribution_level ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ak_promoter_relations ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ak_commission_logs ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ak_distribution_divisions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ak_distribution_agents ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ak_distribution_agent_applications ENABLE ROW LEVEL SECURITY;

-- 1. 分销配置：允许所有登录用户读取（消费者端展示逻辑需要）
DROP POLICY IF EXISTS dist_config_select_policy ON public.ak_distribution_config;
CREATE POLICY dist_config_select_policy ON public.ak_distribution_config 
FOR SELECT TO authenticated USING (deleted_at IS NULL);

-- 2. 分销等级：允许所有登录用户读取可见等级
DROP POLICY IF EXISTS dist_level_select_policy ON public.ak_distribution_level;
CREATE POLICY dist_level_select_policy ON public.ak_distribution_level 
FOR SELECT TO authenticated USING (is_visible = true AND deleted_at IS NULL);

-- 3. 推广员关系：用户仅能查看与自己相关的记录
DROP POLICY IF EXISTS promoter_relations_select_policy ON public.ak_promoter_relations;
CREATE POLICY promoter_relations_select_policy ON public.ak_promoter_relations 
FOR SELECT TO authenticated USING ((uid = auth.uid() OR inviter_uid = auth.uid()) AND deleted_at IS NULL);

-- 4. 佣金日志：用户仅能查看自己的佣金记录
DROP POLICY IF EXISTS commission_logs_select_policy ON public.ak_commission_logs;
CREATE POLICY commission_logs_select_policy ON public.ak_commission_logs 
FOR SELECT TO authenticated USING (uid = auth.uid() AND deleted_at IS NULL);

-- 5. 事业部与代理商：允许登录用户查看启用的记录
DROP POLICY IF EXISTS dist_divisions_select_policy ON public.ak_distribution_divisions;
CREATE POLICY dist_divisions_select_policy ON public.ak_distribution_divisions 
FOR SELECT TO authenticated USING (is_enabled = true AND deleted_at IS NULL);

DROP POLICY IF EXISTS dist_agents_select_policy ON public.ak_distribution_agents;
CREATE POLICY dist_agents_select_policy ON public.ak_distribution_agents 
FOR SELECT TO authenticated USING (is_enabled = true AND deleted_at IS NULL);

-- 6. 代理商申请：用户仅能管理自己的申请记录
DROP POLICY IF EXISTS dist_apply_user_policy ON public.ak_distribution_agent_applications;
CREATE POLICY dist_apply_user_policy ON public.ak_distribution_agent_applications 
FOR ALL TO authenticated USING (uid = auth.uid() AND deleted_at IS NULL) WITH CHECK (uid = auth.uid());

-- 管理端全量管理将通过 SECURITY DEFINER 的 RPC 接口执行，此处不再额外开放直接表操作
