package com.ruoyi.app.omgpay;

import com.ruoyi.app.omgpay.dto.OmgNotifyRequest;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.*;

class OmgNotifyFormParserTest {

    private final OmgNotifyFormParser parser = new OmgNotifyFormParser();

    @Test
    void keepsUnknownAndEmptyFieldsForSignatureAndRawReplay() {
        String raw = "MerchantTradeNo=OMG123&CustomField1=&FutureField=A%2BB";

        OmgNotifyRequest request = parser.parse(raw.getBytes(StandardCharsets.UTF_8), "127.0.0.1",
                "application/x-www-form-urlencoded; charset=UTF-8");

        assertTrue(request.isValid());
        assertEquals(raw, request.getRawForm());
        assertEquals("", request.value("CustomField1"));
        assertEquals("A+B", request.value("FutureField"));
        assertEquals(3, request.signingFields().size());
    }

    @Test
    void rejectsDuplicateFieldsAndMalformedEncoding() {
        OmgNotifyRequest duplicate = parser.parse("RtnCode=1&RtnCode=0".getBytes(StandardCharsets.UTF_8),
                "127.0.0.1", "application/x-www-form-urlencoded");
        OmgNotifyRequest malformed = parser.parse("RtnMsg=%ZZ".getBytes(StandardCharsets.UTF_8),
                "127.0.0.1", "application/x-www-form-urlencoded");

        assertFalse(duplicate.isValid());
        assertFalse(malformed.isValid());
    }

    @Test
    void rejectsWrongContentTypeAndOversizedBody() {
        OmgNotifyRequest wrongType = parser.parse("RtnCode=1".getBytes(StandardCharsets.UTF_8),
                "127.0.0.1", "application/json");
        byte[] oversized = new byte[OmgNotifyFormParser.MAX_FORM_BYTES + 1];
        OmgNotifyRequest tooLarge = parser.parse(oversized, "127.0.0.1",
                "application/x-www-form-urlencoded");

        assertFalse(wrongType.isValid());
        assertFalse(tooLarge.isValid());
    }

    @Test
    void acceptsOmgDocumentedTextHtmlClientPostBody() {
        OmgNotifyRequest request = parser.parse("RtnCode=1&CustomField1=".getBytes(StandardCharsets.UTF_8),
                "127.0.0.1", "text/html; charset=UTF-8");

        assertTrue(request.isValid());
        assertEquals("1", request.value("RtnCode"));
    }
}
