-- =====================================================================================
-- Admin 财务功能 - 提现审核 RPC (口径 2)
-- 位置：docs/sql/30_rpc/finance/
-- 版本：v1
-- 描述：提现审核通过时才扣除佣金并生成流水。
-- 安全策略：SECURITY DEFINER, 入口鉴权, 固定 search_path
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_extract_review(
    p_extract_id UUID,
    p_status SMALLINT, -- 1: 通过, -1: 驳回
    p_refusal_reason TEXT DEFAULT NULL
)
RETURNS VOID
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_extract 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_extract FROM public.ml_extract WHERE id = p_extract_id FOR UPDATE;
    IF NOT FOUND THEN RAISE EXCEPTION 'Extract record not found'; END IF;
    IF v_extract.status != 0 THEN RAISE EXCEPTION 'Record already processed'; END IF;

    -- 3. 业务处理
    IF p_status = 1 THEN
        -- 审核通过：锁定并校验用户资金
        SELECT * INTO v_user FROM public.ak_users WHERE id = v_extract.uid FOR UPDATE;
        IF v_user.brokerage_price < v_extract.extract_price THEN
            RAISE EXCEPTION 'Insufficient brokerage balance';
        END IF;

        -- 扣除佣金
        UPDATE public.ak_users 
        SET brokerage_price = brokerage_price - v_extract.extract_price 
        WHERE id = v_extract.uid;

        -- 写入资金流水
        INSERT INTO public.ml_user_bill (uid, link_id, pm, title, category, type, number, balance)
        VALUES (
            v_extract.uid, 
            p_extract_id::TEXT, 
            0, -- 支出
            '佣金提现', 
            'brokerage', 
            'extract', 
            v_extract.extract_price,
            v_user.brokerage_price - v_extract.extract_price
        );

        -- 更新提现记录
        UPDATE public.ml_extract 
        SET status = 1, admin_id = auth.uid(), payment_time = now() 
        WHERE id = p_extract_id;

    ELSIF p_status = -1 THEN
        -- 审核驳回：仅更新状态
        UPDATE public.ml_extract 
        SET status = -1, refusal_reason = p_refusal_reason, admin_id = auth.uid() 
        WHERE id = p_extract_id;
    ELSE
        RAISE EXCEPTION 'Invalid status';
    END IF;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_extract_review IS '管理员审核提现申请（口径 2：通过时扣款）';
