package server.logic.ws_protocol.JSON.handlers.tempToTest;

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.tempToTest.entyties.Net_TestUploadFreeAvatar_Request;
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_TestUploadFreeAvatar_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;

import java.util.Base64;

public class Net_TestUploadFreeAvatar_Handler implements JsonMessageHandler {

    private final TestFreeAvatarArweaveService service = new TestFreeAvatarArweaveService();

    @Override
    public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) throws Exception {
        Net_TestUploadFreeAvatar_Request req = (Net_TestUploadFreeAvatar_Request) baseRequest;
        if (ctx == null || !ctx.isAuthenticatedUser()) {
            return NetExceptionResponseFactory.error(req, WireCodes.Status.UNVERIFIED, "NOT_AUTHENTICATED", "Требуется авторизация");
        }

        String fileBase64 = String.valueOf(req.getFileBytesBase64() == null ? "" : req.getFileBytesBase64()).trim();
        String contentType = String.valueOf(req.getContentType() == null ? "" : req.getContentType()).trim();
        if (fileBase64.isBlank() || contentType.isBlank()) {
            return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_FIELDS", "Нужно передать contentType и fileBytesBase64.");
        }

        byte[] fileBytes;
        try {
            fileBytes = Base64.getDecoder().decode(fileBase64);
        } catch (IllegalArgumentException e) {
            return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_BASE64", "fileBytesBase64 должен быть корректным Base64.");
        }

        String login = String.valueOf(ctx.getLogin() == null ? "" : ctx.getLogin()).trim();
        try {
            TestFreeAvatarArweaveService.UploadResult result = service.uploadAvatar(login, contentType, fileBytes, req.getSha256Hex());
            Net_TestUploadFreeAvatar_Response resp = new Net_TestUploadFreeAvatar_Response();
            resp.setOp(req.getOp());
            resp.setRequestId(req.getRequestId());
            resp.setStatus(WireCodes.Status.OK);
            resp.setTxId(result.txId());
            resp.setSha256Hex(result.sha256Hex());
            resp.setUsedCount(result.usedCount());
            resp.setRemainingCount(result.remainingCount());
            resp.setLimit(result.limit());
            resp.setGateway(result.gateway());
            return resp;
        } catch (TestFreeAvatarArweaveService.FreeAvatarLimitExceededException e) {
            return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "FREE_AVATAR_LIMIT_EXHAUSTED", e.getMessage());
        } catch (IllegalArgumentException e) {
            return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_AVATAR_FILE", e.getMessage());
        } catch (IllegalStateException e) {
            return NetExceptionResponseFactory.error(req, WireCodes.Status.SERVER_DATA_ERROR, "FREE_AVATAR_TEMP_DISABLED", e.getMessage());
        }
    }
}
