package com.lingniu.ingest.protocol.jt808.codec;

import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

class Jt808FrameDecoderTest {

    @Test
    void garbageWithoutFrameBoundaryEmitsMalformedCandidate() {
        EmbeddedChannel channel = new EmbeddedChannel(new Jt808FrameDecoder());

        channel.writeInbound(Unpooled.wrappedBuffer(new byte[]{0x01, 0x02, 0x03}));

        Jt808MalformedFrame malformed = channel.readInbound();
        assertThat(malformed.rawBytes()).containsExactly(0x01, 0x02, 0x03);
        assertThat(malformed.reason()).contains("missing frame boundary");
        assertThat(malformed.peer()).isNotNull();
        assertThat((Object) channel.readInbound()).isNull();
    }

    @Test
    void oversizedUnclosedFrameEmitsMalformedCandidate() {
        byte[] bytes = new byte[16 * 1024 + 2];
        bytes[0] = 0x7e;
        bytes[1] = 0x01;
        EmbeddedChannel channel = new EmbeddedChannel(new Jt808FrameDecoder());

        channel.writeInbound(Unpooled.wrappedBuffer(bytes));

        Jt808MalformedFrame malformed = channel.readInbound();
        assertThat(malformed.rawBytes()).containsExactly(bytes);
        assertThat(malformed.reason()).contains("too large");
        assertThat(malformed.peer()).isNotNull();
        assertThat((Object) channel.readInbound()).isNull();
    }
}
