package com.ruoyi.system.omgpay.service;

import com.ruoyi.system.domain.IpnLog;
import com.ruoyi.system.service.IIpnLogService;
import org.junit.jupiter.api.Test;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

class OmgIpnAuditServiceTest {

    @Test
    void appendsCompleteRawCallbackAsIndependentOmgIpn() throws Exception {
        IIpnLogService logs = mock(IIpnLogService.class);
        when(logs.insertIpnLog(any())).thenReturn(1);
        OmgIpnAuditService service = new OmgIpnAuditService(logs);

        service.append("127.0.0.1", "MerchantTradeNo=FULL&CustomField1=");

        var captor = org.mockito.ArgumentCaptor.forClass(IpnLog.class);
        verify(logs).insertIpnLog(captor.capture());
        assertEquals("omg", captor.getValue().getType());
        assertEquals("MerchantTradeNo=FULL&CustomField1=", captor.getValue().getIpnLog());
        assertNotNull(captor.getValue().getCretim());
        Method append = OmgIpnAuditService.class.getMethod("append", String.class, String.class);
        assertEquals(Propagation.REQUIRES_NEW, append.getAnnotation(Transactional.class).propagation());
    }

    @Test
    void failsWhenIpnRowWasNotInserted() {
        IIpnLogService logs = mock(IIpnLogService.class);
        when(logs.insertIpnLog(any())).thenReturn(0);

        assertThrows(IllegalStateException.class,
                () -> new OmgIpnAuditService(logs).append("127.0.0.1", "RtnCode=1"));
    }
}
