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_UpsertEspPairingSettings_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_UpsertEspPairingSettings_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.dao.EspPairingSettingsDAO;
import shine.db.entities.EspPairingSettingsEntry;

public class Net_UpsertEspPairingSettings_Handler implements JsonMessageHandler {

    @Override
    public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) throws Exception {
        Net_UpsertEspPairingSettings_Request req = (Net_UpsertEspPairingSettings_Request) baseReq;

        if (!EspPairingSupport.isTrustedUserSession(ctx)) {
            return NetExceptionResponseFactory.error(
                    req,
                    EspPairingSupport.STATUS_PAIRING_REQUIRES_AUTH_SESSION,
                    "PAIRING_REQUIRES_AUTH_SESSION",
                    "Операция доступна только для авторизованной доверенной сессии пользователя"
            );
        }

        boolean enabled = req.getEnabled() != null && req.getEnabled();
        String passwordHash = EspPairingSupport.normalizeOpaqueHash(req.getPasswordHash());
        int ttlSeconds = EspPairingSupport.normalizeTtlSeconds(req.getTtlSeconds());
        if (enabled && (passwordHash == null || passwordHash.isBlank())) {
            return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "EMPTY_PASSWORD_HASH", "Для включения pairing нужен passwordHash");
        }

        long now = System.currentTimeMillis();
        EspPairingSettingsEntry entry = new EspPairingSettingsEntry();
        entry.setLogin(ctx.getLogin());
        entry.setEnabled(enabled);
        entry.setPasswordHash(passwordHash == null ? "" : passwordHash);
        entry.setTtlSeconds(ttlSeconds);
        entry.setFailedAttempts(0);
        entry.setFirstFailedAtMs(0L);
        entry.setBlockedUntilMs(0L);
        entry.setUpdatedAtMs(now);
        EspPairingSettingsDAO.getInstance().upsert(entry);

        Net_UpsertEspPairingSettings_Response resp = new Net_UpsertEspPairingSettings_Response();
        resp.setOp(req.getOp());
        resp.setRequestId(req.getRequestId());
        resp.setStatus(WireCodes.Status.OK);
        resp.setEnabled(enabled);
        resp.setTtlSeconds(ttlSeconds);
        return resp;
    }
}
