package server.logic.ws_protocol.JSON.handlers.auth;

import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_GetEspPairingStatus_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_GetEspPairingStatus_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.dao.EspPairingRequestsDAO;
import shine.db.entities.EspPairingRequestEntry;

public class Net_GetEspPairingStatus_Handler implements JsonMessageHandler {

    @Override
    public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) throws Exception {
        Net_GetEspPairingStatus_Request req = (Net_GetEspPairingStatus_Request) baseReq;
        String pairingId = req.getPairingId() == null ? "" : req.getPairingId().trim();
        if (pairingId.isBlank()) {
            return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "EMPTY_PAIRING_ID", "Пустой pairingId");
        }

        long now = System.currentTimeMillis();
        EspPairingRequestsDAO.getInstance().expirePending(now);
        EspPairingRequestEntry row = EspPairingRequestsDAO.getInstance().getByPairingId(pairingId);
        if (row == null) {
            return NetExceptionResponseFactory.error(req, 404, "PAIRING_NOT_FOUND", "Pairing-заявка не найдена");
        }

        String state = row.getStatus();
        if (row.getExpiresAtMs() <= now && EspPairingSupport.STATE_CREATED.equals(state)) {
            state = EspPairingSupport.STATE_EXPIRED;
        }

        Net_GetEspPairingStatus_Response resp = new Net_GetEspPairingStatus_Response();
        resp.setOp(req.getOp());
        resp.setRequestId(req.getRequestId());
        resp.setStatus(WireCodes.Status.OK);
        resp.setPairingId(row.getPairingId());
        resp.setState(state);
        resp.setShortCode(row.getShortCode());
        resp.setFingerprintB58(row.getFingerprintB58());
        resp.setPayloadType(row.getPayloadType());
        resp.setEncryptedPayload(row.getEncryptedPayload());
        resp.setRejectReason(row.getRejectReason());
        resp.setExpiresAtMs(row.getExpiresAtMs());
        return resp;
    }
}
