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

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import java.util.Arrays;
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.web.modules.region.domain.BizRegion;
import com.ruoyi.web.modules.region.mapper.BizRegionMapper;
import com.ruoyi.web.modules.region.service.impl.RegionServiceImpl;
import com.ruoyi.web.modules.region.vo.RegionTreeVO;

@ExtendWith(MockitoExtension.class)
class RegionServiceImplTest
{
    @Mock
    private BizRegionMapper regionMapper;

    @InjectMocks
    private RegionServiceImpl regionService;

    @Test
    void getRegionTree_buildsThreeLevels()
    {
        BizRegion province = region("北京市", 1, 0, 1, 110000);
        BizRegion city = region("市辖区", 32, 1, 2, 110100);
        BizRegion district = region("东城区", 100, 32, 3, 110101);
        when(regionMapper.selectAll()).thenReturn(Arrays.asList(province, city, district));

        RegionTreeVO root = regionService.getRegionTree().get(0);
        assertEquals("北京市", root.getName());
        assertEquals(1, root.getType());
        assertEquals(1, root.getChildren().size());
        assertEquals("市辖区", root.getChildren().get(0).getName());
        assertEquals(1, root.getChildren().get(0).getChildren().size());
        assertEquals("东城区", root.getChildren().get(0).getChildren().get(0).getName());
    }

    @Test
    void getRegionTree_usesCacheOnSecondCall()
    {
        when(regionMapper.selectAll()).thenReturn(Arrays.asList(region("河北省", 3, 0, 1, 130000)));

        assertEquals(1, regionService.getRegionTree().size());
        assertEquals(1, regionService.getRegionTree().size());
        assertTrue(regionService.getRegionTree().get(0).getName().equals("河北省"));
    }

    private static BizRegion region(String name, int id, int pid, int type, int code)
    {
        BizRegion row = new BizRegion();
        row.setId(id);
        row.setPid(pid);
        row.setName(name);
        row.setType(type);
        row.setCode(code);
        return row;
    }
}
