package com.ruoyi.web.modules.trading.service.impl;

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.ArgumentMatchers.argThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.trading.domain.BizMarketStall;
import com.ruoyi.web.modules.trading.mapper.BizMarketStallMapper;
import com.ruoyi.web.modules.trading.support.MarketStallReferenceChecker;
import com.ruoyi.web.modules.trading.support.MarketStallRules;
import com.ruoyi.web.modules.trading.support.StallCodeGenerator;
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;

@ExtendWith(MockitoExtension.class)
@DisplayName("BizMarketStallServiceImpl")
class BizMarketStallServiceImplTest
{
    @Mock
    private BizMarketStallMapper mapper;

    @Mock
    private StallCodeGenerator stallCodeGenerator;

    @Mock
    private MarketStallReferenceChecker referenceChecker;

    @InjectMocks
    private BizMarketStallServiceImpl service;

    @Test
    @DisplayName("新增分配编号")
    void insert()
    {
        when(stallCodeGenerator.allocateNextCode()).thenReturn("03");
        when(mapper.insertBizMarketStall(any())).thenReturn(1);
        BizMarketStall row = new BizMarketStall();
        row.setRemark("A区东侧");
        assertEquals(1, service.insertBizMarketStall(row));
        verify(mapper).insertBizMarketStall(argThat(r -> "03".equals(r.getStallCode())
                && MarketStallRules.DEL_FLAG_NORMAL.equals(r.getDelFlag())));
    }

    @Test
    @DisplayName("不可改编号")
    void updateCodeBlocked()
    {
        BizMarketStall db = new BizMarketStall();
        db.setId(1L);
        db.setStallCode("01");
        when(mapper.selectBizMarketStallById(1L)).thenReturn(db);
        BizMarketStall in = new BizMarketStall();
        in.setId(1L);
        in.setStallCode("99");
        assertThrows(ServiceException.class, () -> service.updateBizMarketStall(in));
        verify(mapper, never()).updateBizMarketStall(any());
    }

    @Test
    @DisplayName("删除有关联拒绝")
    void deleteWithReference()
    {
        BizMarketStall db = new BizMarketStall();
        db.setId(5L);
        db.setStallCode("05");
        db.setDelFlag(MarketStallRules.DEL_FLAG_NORMAL);
        when(mapper.selectBizMarketStallByIdAny(5L)).thenReturn(db);
        when(referenceChecker.hasReference(5L)).thenReturn(true);
        assertThrows(ServiceException.class, () -> service.deleteBizMarketStallByIds(new Long[] { 5L }, "tester"));
        verify(mapper, never()).logicDeleteBizMarketStallByIds(any(), any());
    }
}
