package com.ruoyi.app.omgpay;

import jakarta.servlet.ServletRequest;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;

class OmgNotifyRawBodyFilterTest {

    @Test
    void preservesNotifyBodyForLaterMvcResolution() throws Exception {
        String raw = "MerchantTradeNo=FULL&CustomField1=";
        MockHttpServletRequest request = new MockHttpServletRequest("POST", "/pay/omg/notify");
        request.setContentType("application/x-www-form-urlencoded");
        request.setContent(raw.getBytes(StandardCharsets.UTF_8));
        MockFilterChain chain = new MockFilterChain();

        new OmgNotifyRawBodyFilter().doFilter(request, new MockHttpServletResponse(), chain);

        ServletRequest wrapped = chain.getRequest();
        assertEquals(raw, new String(wrapped.getInputStream().readAllBytes(), StandardCharsets.UTF_8));
    }

    @Test
    void preservesPaymentResultButDoesNotWrapUnrelatedRequests() throws Exception {
        OmgNotifyRawBodyFilter filter = new OmgNotifyRawBodyFilter();
        MockHttpServletRequest result = new MockHttpServletRequest("POST", "/pay/omg/result");
        result.setContent("MerchantTradeNo=FULL".getBytes(StandardCharsets.UTF_8));
        MockFilterChain resultChain = new MockFilterChain();
        filter.doFilter(result, new MockHttpServletResponse(), resultChain);
        assertEquals("MerchantTradeNo=FULL", new String(
                resultChain.getRequest().getInputStream().readAllBytes(), StandardCharsets.UTF_8));

        MockHttpServletRequest request = new MockHttpServletRequest("POST", "/pay/omg/query");
        MockFilterChain chain = new MockFilterChain();
        filter.doFilter(request, new MockHttpServletResponse(), chain);
        assertSame(request, chain.getRequest());
    }
}
