package com.lingniu.ingest.core.dispatcher;

import com.lingniu.ingest.api.event.VehicleEvent;
import com.lingniu.ingest.api.pipeline.IngestContext;
import com.lingniu.ingest.api.pipeline.RawFrame;

import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.List;

/**
 * 反射调用 Handler。单独抽出是为了后续可插拔：未来可替换为 MethodHandle 或字节码生成。
 */
public class HandlerInvoker {

    @SuppressWarnings("unchecked")
    public List<VehicleEvent> invoke(HandlerDefinition def, RawFrame frame, IngestContext ctx) {
        try {
            Object result = def.method().invoke(def.bean(), frame.payload());
            return switch (result) {
                case null -> Collections.emptyList();
                case VehicleEvent e -> List.of(e);
                // Handler 可以一次产出多个领域事件，例如 GB32960 0x02 同时产出 Realtime/Location/Alarm。
                case List<?> list -> (List<VehicleEvent>) list;
                default -> throw new IllegalStateException(
                        "Handler return type must be VehicleEvent or List<VehicleEvent>: " + def.method());
            };
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Handler threw exception: " + def.method(), e.getCause());
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Handler not accessible: " + def.method(), e);
        }
    }
}
