package lc.ris.svc;

import lc.eo.EOBsonId;
import lc.eo.EOClient;
import lc.mecha.fabric.HandlerStatus;
import lc.mecha.http.server.HttpTransaction;
import lc.mecha.http.server.PrefixedHandler;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import lc.ris.client.InventoryServiceAPI;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

public class TagUpdateHandler extends PrefixedHandler {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(TagUpdateHandler.class);
    private final EOClient client;

    public TagUpdateHandler(EOClient client, Set<String> pathPrefixes) {
        super(pathPrefixes);
        this.client = client;
    }

    @Override
    public HandlerStatus handlePrefixedWebRequest(HttpTransaction request) throws Throwable {
        var id = request.httpServletRequest.getParameter(InventoryServiceAPI.KEY_LCIT);
        var name = request.httpServletRequest.getParameter(InventoryServiceAPI.KEY_NAME);
        var desc = request.httpServletRequest.getParameter(InventoryServiceAPI.KEY_DESC);

        try (var txn = client.getTransaction("ris_test")) {
            var cnt = txn.objUpdate(new EOBsonId(id), Map.of(InventoryServiceAPI.KEY_NAME, name,
                    InventoryServiceAPI.KEY_DESC, desc), true);
            txn.commit();
            logger.info("Modified count: {}", cnt);
        }

        request.httpServletResponse.getOutputStream().write("Item Updated".getBytes(StandardCharsets.UTF_8));
        return HandlerStatus.BREAK;
    }
}
