package tech.easyflow.admin.controller.system;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import jakarta.servlet.http.HttpServletRequest;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.system.entity.SysLog;
import tech.easyflow.system.mapper.SysLogMapper;
import tech.easyflow.system.service.SysLogService;

import java.util.Collections;

import static org.testng.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * {@link SysLogController} 查询边界测试。
 */
public class SysLogControllerTest {

    /**
     * 清理 MyBatis-Flex 关系查询线程配置。
     */
    @AfterMethod
    public void tearDown() {
        RelationManager.clearQueryRelations();
    }

    /**
     * 验证日志分页最多返回一百条。
     */
    @Test
    public void queryPageShouldClampPageSize() {
        SysLogService service = mock(SysLogService.class);
        SysLogMapper mapper = mock(SysLogMapper.class);
        when(service.getMapper()).thenReturn(mapper);
        when(mapper.paginateWithRelations(any(Page.class), any(QueryWrapper.class)))
                .thenAnswer(invocation -> invocation.getArgument(0));
        SysLogController controller = new SysLogController(service);
        Page<SysLog> page = new Page<>(1, 500);

        Page<SysLog> result = controller.queryPage(page, QueryWrapper.create());

        assertEquals(100L, result.getPageSize());
    }

    /**
     * 验证日志默认按操作时间稳定倒序排列。
     */
    @Test
    public void defaultOrderShouldUseCreatedAndId() {
        SysLogController controller = new SysLogController(mock(SysLogService.class));

        assertEquals(controller.getDefaultOrderBy(), "created desc, id desc");
    }

    /**
     * 验证错误的时间格式会返回明确的业务参数错误。
     */
    @Test(expectedExceptions = BusinessException.class)
    public void buildQueryWrapperShouldRejectInvalidTime() {
        SysLogController controller = new SysLogController(mock(SysLogService.class));
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getParameterMap()).thenReturn(Collections.emptyMap());
        when(request.getParameter("createdStart")).thenReturn("2026/07/30");

        controller.buildQueryWrapper(request);
    }
}
