-- =====================================================================================
-- Schema: 分销事业部管理表
-- 位置：docs/sql/10_schema/distribution/ak_distribution_divisions_v1.sql
-- 说明：管理分销体系中的事业部，支持独立分销比例、邀请码及有效期，按商家隔离。
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ak_distribution_divisions (
    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), -- 事业部负责人UID
    name TEXT NOT NULL,                          -- 事业部名称
    invite_code TEXT UNIQUE NOT NULL,            -- 事业部专属邀请码
    
    ratio DECIMAL(5,2) DEFAULT 0,                -- 事业部额外分销比例 (%)
    agent_count INTEGER DEFAULT 0,               -- 下属代理商数量 (由程序或触发器维护)
    
    end_time TIMESTAMPTZ,                        -- 协议截止时间
    status BOOLEAN DEFAULT true,                 -- 状态: true开启, false关闭
    
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now(),

    -- 约束：一个用户在一个商家下只能负责一个事业部
    UNIQUE(merchant_id, uid)
);

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

-- 权限策略
CREATE POLICY "Merchants manage their own divisions" 
ON public.ak_distribution_divisions FOR ALL 
TO authenticated
USING (merchant_id = auth.uid())
WITH CHECK (merchant_id = auth.uid());

-- 允许查看
CREATE POLICY "Authenticated users view active divisions" 
ON public.ak_distribution_divisions FOR SELECT 
TO authenticated
USING (status = true);

-- 索引
CREATE INDEX IF NOT EXISTS idx_divisions_merchant ON public.ak_distribution_divisions(merchant_id);
CREATE INDEX IF NOT EXISTS idx_divisions_uid ON public.ak_distribution_divisions(uid);
