-- RPC: rpc_admin_process_agent_apply
-- 管理端审核代理商申请
-- 若通过(approved)，则同步在 ak_distribution_agents 中创建或更新记录

CREATE OR REPLACE FUNCTION public.rpc_admin_process_agent_apply(
  p_id uuid,
  p_status text, -- approved / rejected
  p_refusal_reason text DEFAULT NULL
)
RETURNS boolean
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  v_uid uuid;
  v_division_uid uuid;
  v_agent_name text;
BEGIN
  -- 仅管理员可审核
  IF NOT EXISTS (
    SELECT 1 FROM public.ak_users u
    WHERE u.id = auth.uid() AND u.role = 'admin'
  ) THEN
    RAISE EXCEPTION 'permission denied';
  END IF;

  -- 1. 获取并锁定申请记录
  SELECT uid, division_uid, agent_name 
  INTO v_uid, v_division_uid, v_agent_name
  FROM public.ak_distribution_agent_applications
  WHERE id = p_id;

  IF v_uid IS NULL THEN
    RAISE EXCEPTION 'application record not found';
  END IF;

  -- 2. 更新申请状态
  UPDATE public.ak_distribution_agent_applications
  SET 
    status = p_status,
    refusal_reason = CASE WHEN p_status = 'rejected' THEN p_refusal_reason ELSE NULL END,
    approved_at = now(),
    approved_by = auth.uid(),
    updated_at = now()
  WHERE id = p_id;

  -- 3. 如果通过，则同步到代理商正式表
  IF p_status = 'approved' THEN
    INSERT INTO public.ak_distribution_agents (
      uid, division_uid, name, commission_ratio, is_enabled, updated_at, updated_by
    )
    VALUES (
      v_uid, v_division_uid, v_agent_name, 0, true, now(), auth.uid()
    )
    ON CONFLICT (uid) DO UPDATE
    SET
      division_uid = EXCLUDED.division_uid,
      name = EXCLUDED.name,
      updated_at = now(),
      updated_by = auth.uid();
  END IF;

  RETURN true;
END;
$$;

REVOKE ALL ON FUNCTION public.rpc_admin_process_agent_apply(uuid, text, text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_process_agent_apply(uuid, text, text) TO authenticated;
