package com.xfestudio.xfeservermanager.infra.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;

/** A single strict UTF-8 JSON boundary used by the embedded API. */
public final class JsonCodec {
    private final Gson gson;

    public JsonCodec() {
        this.gson = new GsonBuilder()
                .registerTypeAdapter(Instant.class, (com.google.gson.JsonSerializer<Instant>)
                        (value, type, context) -> new JsonPrimitive(value.toString()))
                .registerTypeAdapter(Instant.class, (com.google.gson.JsonDeserializer<Instant>)
                        (value, type, context) -> Instant.parse(value.getAsString()))
                .registerTypeAdapter(Duration.class, (com.google.gson.JsonSerializer<Duration>)
                        (value, type, context) -> new JsonPrimitive(value.toMillis()))
                .registerTypeAdapter(Duration.class, (com.google.gson.JsonDeserializer<Duration>)
                        (value, type, context) -> Duration.ofMillis(value.getAsLong()))
                .disableHtmlEscaping()
                .serializeNulls()
                .create();
    }

    public <T> T read(InputStream input, Type type, long contentLength, int maximumBytes)
            throws IOException {
        if (contentLength > maximumBytes) {
            throw new PayloadTooLargeException(maximumBytes);
        }
        try (var bounded = new BoundedInputStream(input, maximumBytes);
                var reader = new InputStreamReader(bounded, StandardCharsets.UTF_8)) {
            T value = gson.fromJson(reader, type);
            if (value == null) {
                throw new JsonParseException("request body must not be null");
            }
            return value;
        }
    }

    public byte[] writeBytes(Object value) {
        return gson.toJson(value).getBytes(StandardCharsets.UTF_8);
    }

    public void write(java.io.OutputStream output, Object value) throws IOException {
        try (var writer = new OutputStreamWriter(output, StandardCharsets.UTF_8)) {
            gson.toJson(value, writer);
        }
    }

    public static final class PayloadTooLargeException extends IOException {
        private static final long serialVersionUID = 1L;

        public PayloadTooLargeException(int maximumBytes) {
            super("payload exceeds " + maximumBytes + " bytes");
        }
    }

    private static final class BoundedInputStream extends InputStream {
        private final InputStream delegate;
        private final long limit;
        private long read;

        private BoundedInputStream(InputStream delegate, long limit) {
            this.delegate = delegate;
            this.limit = limit;
        }

        @Override
        public int read() throws IOException {
            if (read >= limit) {
                int overflow = delegate.read();
                if (overflow < 0) {
                    return -1;
                }
                throw new PayloadTooLargeException((int) limit);
            }
            int value = delegate.read();
            if (value >= 0) {
                read++;
            }
            return value;
        }

        @Override
        public int read(byte[] bytes, int offset, int length) throws IOException {
            int allowed = (int) Math.min(length, limit - read + 1);
            if (allowed <= 0) {
                throw new PayloadTooLargeException((int) limit);
            }
            int count = delegate.read(bytes, offset, allowed);
            if (count > 0) {
                read += count;
                if (read > limit) {
                    throw new PayloadTooLargeException((int) limit);
                }
            }
            return count;
        }
        @Override
        public void close() throws IOException {
            delegate.close();
        }
    }
}
