-- =====================================================================================
-- Schema: 分销代理商管理表
-- 位置：docs/sql/10_schema/distribution/ak_distribution_agents_v1.sql
-- 说明：管理事业部旗下的代理商，按商家隔离。
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ak_distribution_agents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    merchant_id UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    division_id UUID NOT NULL REFERENCES public.ak_distribution_divisions(id) ON DELETE CASCADE,
    uid UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    
    name TEXT NOT NULL,                          -- 代理商名称（或备注名）
    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_agents ENABLE ROW LEVEL SECURITY;

-- 权限策略：商家仅能管理自己的代理商
CREATE POLICY "Merchants manage their own agents" 
ON public.ak_distribution_agents FOR ALL 
TO authenticated
USING (merchant_id = auth.uid())
WITH CHECK (merchant_id = auth.uid());

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

-- 索引
CREATE INDEX IF NOT EXISTS idx_agents_merchant ON public.ak_distribution_agents(merchant_id);
CREATE INDEX IF NOT EXISTS idx_agents_division ON public.ak_distribution_agents(division_id);
