package com.ruoyi.web.modules.store.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 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.store.constant.ShopConstants;
import com.ruoyi.web.modules.store.constant.ShopGlobalConfigConstants;
import com.ruoyi.web.modules.store.domain.BizShopGlobalConfig;
import com.ruoyi.web.modules.store.dto.ShopSettingsDTO;
import com.ruoyi.web.modules.store.mapper.BizShopGlobalConfigMapper;
import com.ruoyi.web.modules.store.service.impl.ShopGlobalConfigServiceImpl;
import com.ruoyi.web.modules.store.vo.ShopSettingsVO;

@ExtendWith(MockitoExtension.class)
class ShopGlobalConfigServiceImplTest
{
    @Mock
    private BizShopGlobalConfigMapper globalConfigMapper;

    @InjectMocks
    private ShopGlobalConfigServiceImpl globalConfigService;

    @Test
    void getGlobalSettings_returnsConfig()
    {
        when(globalConfigMapper.selectById(ShopGlobalConfigConstants.CONFIG_ID)).thenReturn(config());

        ShopSettingsVO vo = globalConfigService.getGlobalSettings();

        assertEquals(ShopConstants.AUDIT_PASS_NO, vo.getDefaultAuditPass());
        assertEquals(5, vo.getMaxSubAdmin());
    }

    @Test
    void getDefaultAuditPass_lazyInitWhenMissing()
    {
        when(globalConfigMapper.selectById(ShopGlobalConfigConstants.CONFIG_ID)).thenReturn(null, config());

        assertEquals(ShopConstants.AUDIT_PASS_NO, globalConfigService.getDefaultAuditPass());
        verify(globalConfigMapper).insert(any(BizShopGlobalConfig.class));
    }

    @Test
    void updateGlobalSettings_invalidAuditPass()
    {
        ShopSettingsDTO dto = new ShopSettingsDTO();
        dto.setDefaultAuditPass("9");
        dto.setMaxSubAdmin(5);

        assertThrows(ServiceException.class, () -> globalConfigService.updateGlobalSettings(dto, "admin"));
        verify(globalConfigMapper, never()).update(any());
    }

    @Test
    void updateGlobalSettings_success()
    {
        ShopSettingsDTO dto = new ShopSettingsDTO();
        dto.setDefaultAuditPass(ShopConstants.AUDIT_PASS_YES);
        dto.setMaxSubAdmin(10);

        globalConfigService.updateGlobalSettings(dto, "admin");

        verify(globalConfigMapper).update(any(BizShopGlobalConfig.class));
    }

    private BizShopGlobalConfig config()
    {
        BizShopGlobalConfig c = new BizShopGlobalConfig();
        c.setConfigId(ShopGlobalConfigConstants.CONFIG_ID);
        c.setDefaultAuditPass(ShopConstants.AUDIT_PASS_NO);
        c.setMaxSubAdmin(5);
        return c;
    }
}
