package com.lingniu.ingest.core.pipeline.builtin;

import com.lingniu.ingest.api.ProtocolId;
import com.lingniu.ingest.api.pipeline.IngestContext;
import com.lingniu.ingest.api.pipeline.RawFrame;
import org.junit.jupiter.api.Test;

import java.time.Instant;
import java.util.Map;

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

class RateLimitInterceptorTest {

    @Test
    void unknownJt808VinUsesPhoneAsIndependentLimiterKey() {
        RateLimitInterceptor interceptor = new RateLimitInterceptor(1, 100);
        IngestContext first = new IngestContext("trace-1");
        IngestContext second = new IngestContext("trace-2");

        boolean firstAllowed = interceptor.before(frame("unknown", "13079970001"), first);
        boolean secondAllowed = interceptor.before(frame("unknown", "13079970002"), second);

        assertThat(firstAllowed).isTrue();
        assertThat(secondAllowed).isTrue();
        assertThat(first.aborted()).isFalse();
        assertThat(second.aborted()).isFalse();
    }

    @Test
    void sameJt808PhoneStillSharesLimiterWhenVinIsUnknown() {
        RateLimitInterceptor interceptor = new RateLimitInterceptor(1, 100);
        IngestContext first = new IngestContext("trace-1");
        IngestContext second = new IngestContext("trace-2");

        boolean firstAllowed = interceptor.before(frame("unknown", "13079970001"), first);
        boolean secondAllowed = interceptor.before(frame("unknown", "13079970001"), second);

        assertThat(firstAllowed).isTrue();
        assertThat(secondAllowed).isFalse();
        assertThat(second.aborted()).isTrue();
        assertThat(second.abortReason()).isEqualTo("rate-limited:phone:13079970001");
    }

    private static RawFrame frame(String vin, String phone) {
        return new RawFrame(
                ProtocolId.JT808,
                0x0200,
                0,
                new Object(),
                new byte[]{0x01},
                Map.of("vin", vin, "phone", phone),
                Instant.parse("2026-06-29T00:00:00Z"));
    }
}
