-- RPC: rpc_admin_get_delivery_staff_list
-- 管理端获取服务人员分页列表（v2）

DROP FUNCTION IF EXISTS public.rpc_admin_get_delivery_staff_list(TEXT, SMALLINT, INTEGER, INTEGER);

CREATE OR REPLACE FUNCTION public.rpc_admin_get_delivery_staff_list(
    p_search TEXT DEFAULT NULL,
    p_status SMALLINT DEFAULT NULL,
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 20
)
RETURNS JSONB
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_offset INTEGER := (p_page - 1) * p_page_size;
    v_total BIGINT;
    v_items JSONB;
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users
        WHERE auth_id = auth.uid() AND role = 'admin'
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    SELECT COUNT(*) INTO v_total
    FROM public.ml_delivery_staff s
    WHERE s.deleted_at IS NULL
      AND (p_status IS NULL OR s.status = p_status)
      AND (
        p_search IS NULL OR p_search = ''
        OR s.nickname ILIKE '%' || p_search || '%'
        OR s.phone ILIKE '%' || p_search || '%'
        OR s.staff_no ILIKE '%' || p_search || '%'
      );

    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT
            s.id,
            s.uid,
            s.station_id,
            st.name AS station_name,
            s.staff_no,
            s.nickname,
            s.avatar,
            s.phone,
            s.status,
            s.is_active,
            s.online_status,
            s.certificate_status,
            s.certificate_expire_at,
            s.service_area,
            s.skills,
            s.created_at,
            s.updated_at
        FROM public.ml_delivery_staff s
        LEFT JOIN public.ml_delivery_stations st ON st.id = s.station_id AND st.deleted_at IS NULL
        WHERE s.deleted_at IS NULL
          AND (p_status IS NULL OR s.status = p_status)
          AND (
            p_search IS NULL OR p_search = ''
            OR s.nickname ILIKE '%' || p_search || '%'
            OR s.phone ILIKE '%' || p_search || '%'
            OR s.staff_no ILIKE '%' || p_search || '%'
          )
        ORDER BY s.created_at DESC
        LIMIT p_page_size OFFSET v_offset
    ) t;

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

REVOKE ALL ON FUNCTION public.rpc_admin_get_delivery_staff_list(TEXT, SMALLINT, INTEGER, INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_get_delivery_staff_list(TEXT, SMALLINT, INTEGER, INTEGER) TO authenticated;