-- =====================================================================================
-- Schema: 分销事业部申请表
-- 位置：docs/sql/10_schema/distribution/ak_distribution_division_applications_v1.sql
-- 说明：记录用户申请加入事业部成为代理商的流水，支持审核流转，按商家隔离。
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ak_distribution_division_applications (
    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) ON DELETE CASCADE,
    
    division_id UUID NOT NULL REFERENCES public.ak_distribution_divisions(id) ON DELETE CASCADE,
    
    name TEXT NOT NULL,                          -- 申请人填写的代理商名称
    phone TEXT NOT NULL,                         -- 申请人联系电话
    images JSONB DEFAULT '[]'::jsonb,            -- 申请附件图片 (数组)
    
    status INTEGER DEFAULT 1,                    -- 状态: 1待审核, 2已同意, 3已拒绝
    admin_remark TEXT,                           -- 审核备注
    
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

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

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

-- 允许用户提交和查看自己的申请
CREATE POLICY "Users handle own applications" 
ON public.ak_distribution_division_applications FOR ALL 
TO authenticated
USING (uid = auth.uid())
WITH CHECK (uid = auth.uid());

-- 索引
CREATE INDEX IF NOT EXISTS idx_div_app_merchant ON public.ak_distribution_division_applications(merchant_id);
CREATE INDEX IF NOT EXISTS idx_div_app_uid ON public.ak_distribution_division_applications(uid);
CREATE INDEX IF NOT EXISTS idx_div_app_status ON public.ak_distribution_division_applications(status);
