-- =====================================================================================
-- Admin 财务功能 - 充值补单/审计 RPC
-- 位置：docs/sql/30_rpc/finance/
-- 版本：v1
-- 描述：由管理员发起的人工充值补单或离线支付审计确认。
-- 安全策略：SECURITY DEFINER, 入口鉴权, 固定 search_path
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_recharge_audit(
    p_recharge_id UUID,
    p_mark TEXT DEFAULT '管理员人工审计/补单'
)
RETURNS VOID
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_recharge RECORD;
    v_user RECORD;
BEGIN
    -- 1. 鉴权：仅 admin 角色可执行
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE id = auth.uid() AND role = 'admin'
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 锁定并获取充值记录
    SELECT * INTO v_recharge FROM public.ml_user_recharge WHERE id = p_recharge_id FOR UPDATE;
    IF NOT FOUND THEN RAISE EXCEPTION 'Recharge record not found'; END IF;
    IF v_recharge.paid = 1 THEN RAISE EXCEPTION 'Recharge already paid'; END IF;

    -- 3. 锁定并更新用户余额
    SELECT * INTO v_user FROM public.ak_users WHERE id = v_recharge.uid FOR UPDATE;
    
    UPDATE public.ak_users 
    SET now_money = now_money + v_recharge.price + v_recharge.give_price 
    WHERE id = v_recharge.uid;

    -- 4. 写入资金流水
    INSERT INTO public.ml_user_bill (uid, link_id, pm, title, category, type, number, balance, mark)
    VALUES (
        v_recharge.uid, 
        v_recharge.order_no, 
        1, -- 收入
        '用户充值', 
        'now_money', 
        'recharge', 
        v_recharge.price + v_recharge.give_price,
        v_user.now_money + v_recharge.price + v_recharge.give_price,
        p_mark
    );

    -- 5. 更新充值记录状态
    UPDATE public.ml_user_recharge 
    SET paid = 1, pay_time = now() 
    WHERE id = p_recharge_id;

END;
$$;

COMMENT ON FUNCTION public.rpc_admin_recharge_audit IS '管理员人工审计/补单（更新用户余额并生成流水）';
