-- RPC: rpc_admin_save_agent
-- 管理端新增或更新代理商

CREATE OR REPLACE FUNCTION public.rpc_admin_save_agent(
  p_uid uuid,
  p_division_uid uuid,
  p_name text,
  p_commission_ratio numeric,
  p_is_enabled boolean DEFAULT true,
  p_end_time timestamptz DEFAULT NULL
)
RETURNS uuid
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
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;

  -- 确保事业部存在
  IF NOT EXISTS (
    SELECT 1 FROM public.ak_distribution_divisions WHERE uid = p_division_uid
  ) THEN
    RAISE EXCEPTION 'parent division not found';
  END IF;

  INSERT INTO public.ak_distribution_agents (
    uid, division_uid, name, commission_ratio, is_enabled, end_time, updated_at, updated_by
  )
  VALUES (
    p_uid, p_division_uid, p_name, p_commission_ratio, p_is_enabled, p_end_time, now(), auth.uid()
  )
  ON CONFLICT (uid) DO UPDATE
  SET
    division_uid = EXCLUDED.division_uid,
    name = EXCLUDED.name,
    commission_ratio = EXCLUDED.commission_ratio,
    is_enabled = EXCLUDED.is_enabled,
    end_time = EXCLUDED.end_time,
    updated_at = now(),
    updated_by = auth.uid();

  RETURN p_uid;
END;
$$;

REVOKE ALL ON FUNCTION public.rpc_admin_save_agent(uuid, uuid, text, numeric, boolean, timestamptz) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_save_agent(uuid, uuid, text, numeric, boolean, timestamptz) TO authenticated;
