-- =====================================================================================
-- Schema: 分销代理商申请表
-- 位置：docs/sql/10_schema/distribution/ak_distribution_agent_applications_v1.sql
-- 对象类型：TABLE
-- 版本：v1
-- 依赖：ak_users, ak_distribution_divisions
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ak_distribution_agent_applications (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    uid UUID NOT NULL REFERENCES public.ak_users(id) ON DELETE CASCADE,
    division_uid UUID NOT NULL REFERENCES public.ak_distribution_divisions(uid),

    agent_name TEXT NOT NULL,
    agent_phone TEXT NULL,

    proof_images JSONB NULL, -- 申请凭证图片列表

    status TEXT NOT NULL DEFAULT 'pending', -- pending/approved/rejected
    refusal_reason TEXT NULL,

    approved_at TIMESTAMPTZ NULL,
    approved_by UUID NULL REFERENCES public.ak_users(id),

    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_dist_agent_applications_uid ON public.ak_distribution_agent_applications(uid);
CREATE INDEX IF NOT EXISTS idx_dist_agent_applications_division_uid ON public.ak_distribution_agent_applications(division_uid);
CREATE INDEX IF NOT EXISTS idx_dist_agent_applications_status ON public.ak_distribution_agent_applications(status);

COMMENT ON TABLE public.ak_distribution_agent_applications IS '分销代理商申请记录表';
COMMENT ON COLUMN public.ak_distribution_agent_applications.proof_images IS '申请图片列表(JSON)';
