-- ============================================
-- 配送效率分析（按 assigned_at 统计周期，接单 -> 送达）
-- 依赖表：ml_delivery_tasks, ml_delivery_drivers
-- ============================================

-- 1) 每日趋势：平均时效/平均配送费/总配送费/完成单量
CREATE OR REPLACE FUNCTION public.rpc_delivery_efficiency_daily(
  p_start TIMESTAMPTZ,
  p_end TIMESTAMPTZ
)
RETURNS TABLE (
  day DATE,
  completed_orders INTEGER,
  avg_delivery_minutes NUMERIC,
  total_fee NUMERIC,
  avg_fee NUMERIC
)
LANGUAGE sql
SECURITY DEFINER
SET search_path = public
AS $$
  SELECT
    DATE(t.assigned_at) AS day,
    COUNT(*)::INTEGER AS completed_orders,
    AVG(EXTRACT(EPOCH FROM (t.delivered_at - t.assigned_at)) / 60.0) AS avg_delivery_minutes,
    COALESCE(SUM(t.delivery_fee), 0) AS total_fee,
    AVG(t.delivery_fee) AS avg_fee
  FROM public.ml_delivery_tasks t
  WHERE t.status = 5
    AND t.assigned_at >= p_start
    AND t.assigned_at < p_end
    AND t.delivered_at IS NOT NULL
  GROUP BY DATE(t.assigned_at)
  ORDER BY day;
$$;

-- 2) Top N 配送员：按完成单量排序
CREATE OR REPLACE FUNCTION public.rpc_delivery_efficiency_top_drivers(
  p_start TIMESTAMPTZ,
  p_end TIMESTAMPTZ,
  p_limit INTEGER DEFAULT 10
)
RETURNS TABLE (
  driver_id UUID,
  driver_name TEXT,
  orders INTEGER,
  rating_avg NUMERIC
)
LANGUAGE sql
SECURITY DEFINER
SET search_path = public
AS $$
  SELECT
    d.id AS driver_id,
    CAST(d.real_name AS TEXT) AS driver_name,
    COUNT(*)::INTEGER AS orders,
    COALESCE(d.rating_avg, 0) AS rating_avg
  FROM public.ml_delivery_tasks t
  JOIN public.ml_delivery_drivers d ON d.id = t.driver_id
  WHERE t.status = 5
    AND t.assigned_at >= p_start
    AND t.assigned_at < p_end
    AND t.delivered_at IS NOT NULL
  GROUP BY d.id, d.real_name, d.rating_avg
  ORDER BY orders DESC
  LIMIT p_limit;
$$;

-- 建议：只允许 authenticated 调用（按你现有 analytics 的做法）
REVOKE ALL ON FUNCTION public.rpc_delivery_efficiency_daily(TIMESTAMPTZ, TIMESTAMPTZ) FROM PUBLIC;
REVOKE ALL ON FUNCTION public.rpc_delivery_efficiency_top_drivers(TIMESTAMPTZ, TIMESTAMPTZ, INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_delivery_efficiency_daily(TIMESTAMPTZ, TIMESTAMPTZ) TO authenticated;
GRANT EXECUTE ON FUNCTION public.rpc_delivery_efficiency_top_drivers(TIMESTAMPTZ, TIMESTAMPTZ, INTEGER) TO authenticated;
