-- =====================================================================================
-- RPC: rpc_admin_invoice_process
-- 位置：docs/sql/30_rpc/finance/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端处理发票申请（开票或驳回）
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_invoice_process(
    p_id UUID,
    p_status SMALLINT, -- 1: 已开票, -1: 已拒绝
    p_invoice_url TEXT DEFAULT NULL,
    p_refusal_reason TEXT DEFAULT NULL
)
RETURNS BOOLEAN
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_ok BOOLEAN;
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 更新状态
    UPDATE public.ml_invoices
    SET 
        status = p_status,
        invoice_url = CASE WHEN p_status = 1 THEN p_invoice_url ELSE invoice_url END,
        refusal_reason = CASE WHEN p_status = -1 THEN p_refusal_reason ELSE refusal_reason END,
        updated_at = now()
    WHERE id = p_id;

    GET DIAGNOSTICS v_ok = ROW_COUNT;
    RETURN v_ok;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_invoice_process IS '管理员处理发票开票申请';
