package com.ruoyi.web.modules.industryservice.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Collections;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.industryservice.domain.dto.YakDiseaseWarningDto;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetSyncResultVo;
import com.ruoyi.web.modules.industryservice.support.ThirdPartyYakAlertClient;
import com.ruoyi.web.modules.industryservice.support.YakDiseaseWarningRules;

@ExtendWith(MockitoExtension.class)
@DisplayName("YakDiseaseWarningSyncService")
class YakDiseaseWarningSyncServiceTest
{
    @Mock
    private ThirdPartyYakAlertClient thirdPartyYakAlertClient;

    @Mock
    private YakDiseaseWarningSyncTxService syncTxService;

    @InjectMocks
    private YakDiseaseWarningSyncService syncService;

    @Test
    @DisplayName("ZCZX-MYNBJY-UT-010 第三方失败不清库")
    void ut010_thirdPartyFail()
    {
        when(thirdPartyYakAlertClient.fetchAlerts()).thenThrow(new ServiceException("超时"));
        assertThrows(ServiceException.class, () -> syncService.syncFromThirdParty());
        verify(syncTxService, never()).persistAlert(any(), any());
    }

    @Test
    @DisplayName("ZCZX-MYNBJY-UT-008 新增计数")
    void ut008_insert()
    {
        YakDiseaseWarningDto dto = new YakDiseaseWarningDto();
        dto.setExternalAlertId("TP-NEW");
        when(thirdPartyYakAlertClient.fetchAlerts()).thenReturn(Collections.singletonList(dto));
        when(syncTxService.persistAlert(any(), any())).thenReturn(true);
        YakAssetSyncResultVo result = syncService.syncFromThirdParty();
        assertEquals(1, result.getInsertCount());
    }

    @Test
    @DisplayName("ZCZX-MYNBJY-UT-012 处理中拒重复")
    void ut012_syncInProgress() throws Exception
    {
        YakDiseaseWarningDto dto = new YakDiseaseWarningDto();
        dto.setExternalAlertId("TP-SLOW");
        when(thirdPartyYakAlertClient.fetchAlerts()).thenAnswer(inv -> {
            Thread.sleep(200);
            return Collections.singletonList(dto);
        });
        when(syncTxService.persistAlert(any(), any())).thenReturn(true);
        Thread t1 = new Thread(() -> syncService.syncFromThirdParty());
        t1.start();
        Thread.sleep(50);
        ServiceException ex = assertThrows(ServiceException.class, () -> syncService.syncFromThirdParty());
        assertEquals(YakDiseaseWarningRules.MSG_SYNC_IN_PROGRESS, ex.getMessage());
        t1.join();
    }
}
