package vassistent.service;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import vassistent.util.Logger;

/**
 * Validates incoming JSON payloads and forwards accepted predictions to storage and evaluation.
 */
public class BinaryEventService {
    private final DataPersistenceService persistenceService;
    private final EvaluationService evaluationService;

    private Integer lastId = null;

    /**
     * Creates a binary event service with required persistence and evaluation dependencies.
     *
     * @param persistenceService service used to persist accepted predictions
     * @param evaluationService service used to recompute risk level after inserts
     */
    public BinaryEventService(
            DataPersistenceService persistenceService,
            EvaluationService evaluationService
    ) {
        this.persistenceService = persistenceService;
        this.evaluationService = evaluationService;
    }

    /**
     * Parses, validates, and processes an incoming MQTT payload.
     *
     * @param payload raw JSON message body
     */
    public synchronized void handlePayload(String payload) {

        try {

            JsonObject json = JsonParser.parseString(payload).getAsJsonObject();

            if (!json.has("valid") || !json.get("valid").getAsBoolean()) {
                Logger.warn("EVENT", "Payload is not valid");
                return;
            }

            if (!json.has("_id") || !json.has("prediction")) {
                Logger.warn("EVENT", "Payload is incomplete");
                return;
            }

            int id = json.get("_id").getAsInt();

            if (lastId != null && lastId == id) {
                Logger.warn("EVENT", "Payload ID already processed: " + id);
                return;
            }

            lastId = id;

            int prediction = json.get("prediction").getAsInt();

            if (prediction != 0 && prediction != 1) {
                Logger.warn("EVENT", "Invalid prediction: " + prediction);
                return;
            }

            persistenceService.store(prediction);
            evaluationService.evaluate();

            Logger.debug("EVENT", "Prediction processed: " + prediction);

        } catch (Exception e) {
            Logger.error("EVENT", "Payload processing failed: " + payload, e);
        }
    }
}
