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

public class Net_GetTrustedDeviceLoginSettings_Handler implements JsonMessageHandler {

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

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

        EspPairingSettingsEntry entry = EspPairingSettingsDAO.getInstance().getByLogin(ctx.getLogin());
        boolean enabled = entry == null || entry.isEnabled();
        boolean hasPassword = enabled
                && entry != null
                && entry.getPasswordHash() != null
                && !entry.getPasswordHash().trim().isBlank();

        Net_GetTrustedDeviceLoginSettings_Response resp = new Net_GetTrustedDeviceLoginSettings_Response();
        resp.setOp(req.getOp());
        resp.setRequestId(req.getRequestId());
        resp.setStatus(200);
        resp.setEnabled(enabled);
        resp.setHasPassword(hasPassword);
        return resp;
    }
}
