-- =====================================================================================
-- Admin 统计功能 - 获取全站核心指标概览 RPC
-- 位置：docs/sql/30_rpc/admin/rpc_admin_get_overall_stats_v1.sql
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：一次性聚合查询销售、订单、用户及商品的核心统计指标
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_get_overall_stats()
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_stats JSONB;
    v_today_start TIMESTAMPTZ := CURRENT_DATE;
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE auth_id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 聚合统计
    WITH totals AS (
        SELECT 
            (SELECT COALESCE(SUM(paid_amount), 0) FROM public.ml_orders WHERE paid = 1) as total_sales,
            (SELECT COUNT(*) FROM public.ml_orders WHERE paid = 1) as total_orders,
            (SELECT COUNT(*) FROM public.ak_users) as total_users,
            (SELECT COUNT(*) FROM public.ml_products) as total_products
    ),
    today_stats AS (
        SELECT 
            (SELECT COALESCE(SUM(paid_amount), 0) FROM public.ml_orders WHERE paid = 1 AND created_at >= v_today_start) as today_sales,
            (SELECT COUNT(*) FROM public.ml_orders WHERE paid = 1 AND created_at >= v_today_start) as today_orders,
            (SELECT COUNT(*) FROM public.ak_users WHERE created_at >= v_today_start) as today_new_users
    ),
    pending_tasks AS (
        SELECT 
            (SELECT COUNT(*) FROM public.ml_orders WHERE paid = 1 AND order_status = 1) as pending_delivery,
            (SELECT COUNT(*) FROM public.ml_product_skus WHERE stock <= 10) as stock_warning, -- 假设库存小于10为预警
            (SELECT COUNT(*) FROM public.ml_extract WHERE status = 0) as pending_extract
    )
    SELECT jsonb_build_object(
        'totals', (SELECT row_to_json(totals.*) FROM totals),
        'today', (SELECT row_to_json(today_stats.*) FROM today_stats),
        'pending', (SELECT row_to_json(pending_tasks.*) FROM pending_tasks)
    ) INTO v_stats;

    RETURN v_stats;
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_get_overall_stats() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_get_overall_stats() TO authenticated;
