package lc.ris.svc;

import lc.eo.EOBsonId;
import lc.eo.EOClient;
import lc.eo.json.EOJsonSerializer;
import lc.eo.sdk.EO;
import lc.mecha.fabric.HandlerStatus;
import lc.mecha.http.server.HttpTransaction;
import lc.mecha.http.server.PrefixedHandler;

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

public class TagCreateHandler extends PrefixedHandler {
    private final EOClient client;

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

    @Override
    public HandlerStatus handlePrefixedWebRequest(HttpTransaction request) throws Throwable {
        String type = request.httpServletRequest.getParameter("type");
        if (type == null) {
            request.httpServletResponse.setStatus(400);
            return HandlerStatus.BREAK;
        }

        try (var txn = client.getTransaction("ris_test")) {
            var id = txn.objAdd(type);
            txn.commit();
            EO result = new EO();
            result.setValue("id", TagUtil.encode((EOBsonId) id));
            request.httpServletResponse.getOutputStream().write(EOJsonSerializer.toJson(result).toString().getBytes(StandardCharsets.UTF_8));
        }
        return HandlerStatus.BREAK;
    }
}
