-- 1. 创建分销配置表
CREATE TABLE IF NOT EXISTS public.ak_distribution_config (
    id TEXT PRIMARY KEY DEFAULT 'global_config',
    is_enabled BOOLEAN DEFAULT true,               -- 分销启用
    extract_type TEXT DEFAULT '2',                  -- 分销模式: 1指定, 2人人, 3满额
    bind_type TEXT DEFAULT '2',                     -- 绑定关系: 1所有用户, 2新用户
    store_brokerage_binding_status TEXT DEFAULT '1', -- 绑定模式: 1永久, 2有效期, 3临时
    brokerage_poster_status TEXT,                   -- 分销海报图路径/URL
    brokerage_level INTEGER DEFAULT 2,              -- 分销层级: 1, 2
    is_area_manager BOOLEAN DEFAULT true,           -- 事业部开关
    is_agent_apply BOOLEAN DEFAULT true,            -- 代理商申请开关
    is_commission_window BOOLEAN DEFAULT true,      -- 佣金悬浮窗开关
    
    -- 返佣设置
    is_self_brokerage BOOLEAN DEFAULT true,         -- 自购返佣
    is_member_brokerage BOOLEAN DEFAULT false,      -- 购买会员返佣
    brokerage_type TEXT DEFAULT '1',                -- 返佣类型: 1价格, 2实付
    is_promoter_brokerage BOOLEAN DEFAULT true,     -- 推广用户返佣
    promoter_brokerage_price DECIMAL(10,2) DEFAULT 2.00,
    promoter_brokerage_day_max DECIMAL(10,2) DEFAULT -1.00,
    store_brokerage_ratio DECIMAL(10,2) DEFAULT 20.00,
    store_brokerage_two_ratio DECIMAL(10,2) DEFAULT 2.00,
    extract_frozen_time INTEGER DEFAULT 1,
    
    -- 提现设置
    user_extract_min_price DECIMAL(10,2) DEFAULT 1.00,
    extract_bank_list TEXT DEFAULT '中国银行',
    extract_type_list TEXT[] DEFAULT ARRAY['bank', 'wechat', 'alipay'],
    wechat_extract_type TEXT DEFAULT '1',
    alipay_extract_type TEXT DEFAULT '1',
    user_extract_fee DECIMAL(10,2) DEFAULT 0.00,
    
    updated_at TIMESTAMPTZ DEFAULT now(),
    updated_by UUID REFERENCES auth.users(id)
);

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

-- 3. 创建权限策略 (基于公共角色函数或直接查询 ak_users)
-- 允许 Admin 查看配置
CREATE POLICY "Admins can view distribution config" 
ON public.ak_distribution_config FOR SELECT 
TO authenticated
USING (
  EXISTS (
    SELECT 1 FROM public.ak_users 
    WHERE auth_id = auth.uid() AND role = 'admin'
  )
);

-- 允许 Admin 修改配置
CREATE POLICY "Admins can update distribution config" 
ON public.ak_distribution_config FOR ALL 
TO authenticated
USING (
  EXISTS (
    SELECT 1 FROM public.ak_users 
    WHERE auth_id = auth.uid() AND role = 'admin'
  )
)
WITH CHECK (
  EXISTS (
    SELECT 1 FROM public.ak_users 
    WHERE auth_id = auth.uid() AND role = 'admin'
  )
);

-- 4. 插入初始化数据
INSERT INTO public.ak_distribution_config (id) 
VALUES ('global_config')
ON CONFLICT (id) DO NOTHING;
