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_ListEspPairingRequests_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_ListEspPairingRequests_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;

import java.util.ArrayList;
import java.util.List;

public class Net_ListEspPairingRequests_Handler implements JsonMessageHandler {

    @Override
    public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) throws Exception {
        Net_ListEspPairingRequests_Request req = (Net_ListEspPairingRequests_Request) baseReq;
        if (!EspPairingSupport.isTrustedUserSession(ctx)) {
            return NetExceptionResponseFactory.error(
                    req,
                    EspPairingSupport.STATUS_PAIRING_REQUIRES_AUTH_SESSION,
                    "PAIRING_REQUIRES_AUTH_SESSION",
                    "Операция доступна только для авторизованной доверенной сессии пользователя"
            );
        }

        long now = System.currentTimeMillis();
        EspPairingRequestsDAO.getInstance().expirePending(now);
        List<EspPairingRequestEntry> rows = EspPairingRequestsDAO.getInstance().listActiveByLogin(ctx.getLogin(), now);
        List<Net_ListEspPairingRequests_Response.PairingRequestItem> items = new ArrayList<>();
        for (EspPairingRequestEntry row : rows) {
            Net_ListEspPairingRequests_Response.PairingRequestItem item = new Net_ListEspPairingRequests_Response.PairingRequestItem();
            item.setPairingId(row.getPairingId());
            item.setState(row.getStatus());
            item.setRequesterSessionKey(row.getRequesterSessionKey());
            item.setRequesterSessionType(row.getRequesterSessionType());
            item.setRequesterClientPlatform(row.getRequesterClientPlatform());
            item.setPayloadType(row.getPayloadType());
            item.setShortCode(row.getShortCode());
            item.setFingerprintB58(row.getFingerprintB58());
            item.setCreatedAtMs(row.getCreatedAtMs());
            item.setExpiresAtMs(row.getExpiresAtMs());
            item.setDeliveredToHomeserver(row.isDeliveredToHomeserver());
            items.add(item);
        }

        Net_ListEspPairingRequests_Response resp = new Net_ListEspPairingRequests_Response();
        resp.setOp(req.getOp());
        resp.setRequestId(req.getRequestId());
        resp.setStatus(WireCodes.Status.OK);
        resp.setRequests(items);
        return resp;
    }
}
