package com.zcloud.personnel.positioning.command.query;

import com.alibaba.cola.dto.PageResponse;
import com.zcloud.personnel.positioning.dto.PositionPersonPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.PositionPersonCO;
import com.zcloud.personnel.positioning.integration.finds.FindsOpenApiClient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.Collections;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

class PositionPersonStoredStatusTest {
    private FindsOpenApiClient findsOpenApiClient;
    private PositionPersonLocalLookupService localLookupService;
    private PositionPersonQueryExe queryExe;

    @BeforeEach
    void setUp() {
        findsOpenApiClient = mock(FindsOpenApiClient.class);
        localLookupService = mock(PositionPersonLocalLookupService.class);
        queryExe = new PositionPersonQueryExe(findsOpenApiClient, localLookupService);
    }

    @Test
    void persistedStatusIsUsedWithoutCallingFindsLocate() {
        PositionPersonLocalLookupService.LocalPerson local = new PositionPersonLocalLookupService.LocalPerson();
        local.setUserId(1L);
        local.setStaffName("Stored User");
        local.setMobileNo("13800000001");

        PositionPersonLocalLookupService.PersonMapping mapping =
                new PositionPersonLocalLookupService.PersonMapping();
        mapping.setFindsStaffNo("13800000001");
        mapping.setFindsTerminalNo("T-1");
        mapping.setLocationStatus("ONLINE");
        mapping.setLocal(local);

        when(localLookupService.hasPersonnelMappings()).thenReturn(true);
        when(localLookupService.findMatchedPersonnel(any(PositionPersonPageQry.class)))
                .thenReturn(Collections.singletonList(mapping));
        when(localLookupService.findTerminalNosByIdCardNos(anySet()))
                .thenReturn(Collections.emptyMap());
        when(localLookupService.findTerminals(eq(Collections.singleton("T-1"))))
                .thenReturn(Collections.emptyMap());

        PositionPersonPageQry qry = new PositionPersonPageQry();
        qry.setPageIndex(1);
        qry.setPageSize(20);
        PageResponse<PositionPersonCO> response = queryExe.list(qry);

        assertEquals(1, response.getTotalCount());
        assertEquals("ONLINE", response.getData().get(0).getLocationStatus());
        verify(findsOpenApiClient, never()).postFailFast(eq("finds.point.locate"), anyMap());
    }
}
