-- RPC: rpc_admin_save_division
-- 管理端新增或更新事业部

CREATE OR REPLACE FUNCTION public.rpc_admin_save_division(
  p_uid uuid,
  p_name text,
  p_invite_code 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;

  INSERT INTO public.ak_distribution_divisions (
    uid, name, invite_code, commission_ratio, is_enabled, end_time, updated_at, updated_by
  )
  VALUES (
    p_uid, p_name, p_invite_code, p_commission_ratio, p_is_enabled, p_end_time, now(), auth.uid()
  )
  ON CONFLICT (uid) DO UPDATE
  SET
    name = EXCLUDED.name,
    invite_code = EXCLUDED.invite_code,
    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_division(uuid, text, text, numeric, boolean, timestamptz) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_save_division(uuid, text, text, numeric, boolean, timestamptz) TO authenticated;
