-- =====================================================================================
-- RPC: rpc_admin_invoice_list
-- 位置：docs/sql/30_rpc/finance/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端分页获取发票申请列表，支持搜索、状态筛选及时间过滤
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_invoice_list(
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 15,
    p_status SMALLINT DEFAULT NULL,
    p_start_time TIMESTAMP WITH TIME ZONE DEFAULT NULL,
    p_end_time TIMESTAMP WITH TIME ZONE DEFAULT NULL,
    p_search TEXT DEFAULT NULL
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_offset INTEGER;
    v_total BIGINT;
    v_items JSONB;
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;

    v_offset := (p_page - 1) * p_page_size;

    -- 2. 获取总数
    SELECT COUNT(*) INTO v_total
    FROM public.ml_invoices i
    LEFT JOIN public.ak_users u ON u.id = i.uid
    WHERE (p_status IS NULL OR i.status = p_status)
      AND (p_start_time IS NULL OR i.created_at >= p_start_time)
      AND (p_end_time IS NULL OR i.created_at <= p_end_time)
      AND (p_search IS NULL OR (
          i.order_no ILIKE '%' || p_search || '%' OR
          i.header_name ILIKE '%' || p_search || '%' OR
          u.username ILIKE '%' || p_search || '%'
      ));

    -- 3. 获取明细数据
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            i.id,
            i.uid,
            i.order_no,
            i.order_amount,
            i.invoice_type,
            i.header_type,
            i.header_name,
            i.tax_id,
            i.email,
            i.remark,
            i.status,
            i.refusal_reason,
            i.invoice_url,
            i.created_at,
            i.updated_at,
            u.username as user_name,
            u.email as user_email
        FROM public.ml_invoices i
        LEFT JOIN public.ak_users u ON u.id = i.uid
        WHERE (p_status IS NULL OR i.status = p_status)
          AND (p_start_time IS NULL OR i.created_at >= p_start_time)
          AND (p_end_time IS NULL OR i.created_at <= p_end_time)
          AND (p_search IS NULL OR (
              i.order_no ILIKE '%' || p_search || '%' OR
              i.header_name ILIKE '%' || p_search || '%' OR
              u.username ILIKE '%' || p_search || '%'
          ))
        ORDER BY i.created_at DESC
        LIMIT p_page_size
        OFFSET v_offset
    ) t;

    RETURN jsonb_build_object(
        'total', v_total,
        'items', COALESCE(v_items, '[]'::jsonb)
    );
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_invoice_list IS '管理员分页查询发票申请列表';
