package cd.casic.server;

import cd.casic.ci.process.dto.req.pipeline.PipelineCreateReq;
import cd.casic.ci.process.dto.req.pipeline.PipelineQueryReq;
import cd.casic.ci.process.dto.req.pipeline.PipelineReq;
import cd.casic.ci.process.dto.req.pipeline.PipelineUpdateReq;
import cd.casic.ci.process.dto.resp.pipeline.PipelineFindResp;
import cd.casic.ci.process.dto.resp.template.TemplateFindResp;
import cd.casic.ci.process.dto.resp.template.TemplateStageResp;
import cd.casic.ci.process.dto.resp.template.TemplateTasksResp;
import cd.casic.ci.process.process.service.pipeline.impl.PipelineServiceImpl;
import cd.casic.ci.process.process.service.template.impl.TemplateManagerServiceImpl;
import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.exception.enums.GlobalErrorCodeConstants;
import cd.casic.framework.commons.pojo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;

import java.util.ArrayList;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;

@SpringBootTest(classes = {OpsServerApplication.class})
@ActiveProfiles("local")
@Slf4j
public class PipelineTest {
    @Autowired
    private PipelineServiceImpl pipelineService;

    @MockBean
    private TemplateManagerServiceImpl templateManagerService;

    @BeforeEach
    void setUp() {
        // 模拟当前登录用户 ID
//        when(webFrameworkUtils.getLoginUserId()).thenReturn(1L);
    }

    @Test
    void testCreatePipeline_WithoutTemplateId() {
        PipelineCreateReq req = new PipelineCreateReq();
        req.setName("Test Pipeline");
        req.setTemplateId(null); // 不使用模板

        String result = pipelineService.createPipeline(req);

        assertNotNull(result);
        assertTrue(result.length() > 0);
    }

    @Test
    void testCreatePipeline_WithTemplateId_TemplateNotFound() {
        PipelineCreateReq req = new PipelineCreateReq();
        req.setTemplateId("non-existent-template-id");

        // 模板服务返回 null 表示未找到模板
        when(templateManagerService.findTemplateById("non-existent-template-id")).thenReturn(null);

        String result = pipelineService.createPipeline(req);

        assertNotNull(result);
        assertTrue(result.length() > 0);
    }

    @Test
    void testCreatePipeline_WithTemplateId_TemplateFound_NoStages() {
        PipelineCreateReq req = new PipelineCreateReq();
        req.setTemplateId("empty-template-id");

        TemplateFindResp template = new TemplateFindResp();
        template.setId("empty-template-id");
        template.setStageList(new ArrayList<>());
        //        TemplateFindResp templateFindResp =  new TemplateFindResp();
//        List<TemplateStageResp> stageResps = new ArrayList<>();
//        TemplateStageResp templateStageResp = new TemplateStageResp();
//        List<TemplateTasksResp> childTaskList = new ArrayList<>();
//        List<TemplateStageResp> childStageList = new ArrayList<>();
//
//        templateFindResp.setStageList();

        when(templateManagerService.findTemplateById("empty-template-id")).thenReturn(template);

        String result = pipelineService.createPipeline(req);

        assertNotNull(result);
        assertTrue(result.length() > 0);
    }

    @Test
    void testCreatePipeline_WithTemplateId_TemplateFound_WithStagesAndTasks() {
        PipelineCreateReq req = new PipelineCreateReq();
        req.setTemplateId("valid-template-id");

        TemplateFindResp template = new TemplateFindResp();
        template.setId("valid-template-id");

        // 构建阶段
        TemplateStageResp stage1 = new TemplateStageResp();
        stage1.setId("stage-1");
        stage1.setStageName("Build Stage");
        stage1.setCode(false);

        // 构建子阶段
        TemplateStageResp subStage = new TemplateStageResp();
        subStage.setId("sub-stage-1");
        subStage.setStageName("Sub Build Stage");
        subStage.setCode(true);

        // 构建任务
        TemplateTasksResp task1 = new TemplateTasksResp();
        task1.setId("task-1");
        task1.setTaskName("Maven Build Task");

        subStage.setTaskValues(List.of(task1));
        stage1.setStageList(List.of(subStage));

        template.setStageList(List.of(stage1));

        when(templateManagerService.findTemplateById("valid-template-id")).thenReturn(template);

        String result = pipelineService.createPipeline(req);

        assertNotNull(result);
        assertTrue(result.length() > 0);
    }




    /**
     * 测试正常查询流水线列表
     */
    @Test
    void testFindPipelineList_Normal() {
        PipelineQueryReq req = new PipelineQueryReq();
        req.setName("test-ljc");

        // 验证结果
        List<PipelineFindResp> result = pipelineService.findPipelineList(req);

        assertNotNull(result);
        assertFalse(result.isEmpty());

        result.forEach(p -> {
            assertNotNull(p.getId());
            assertNotNull(p.getName());
            assertNotNull(p.getCreatorName());
        });
    }

    /**
     * 测试无匹配数据时返回空列表
     */
    @Test
    void testFindPipelineList_EmptyResult() {
        PipelineQueryReq req = new PipelineQueryReq();
        req.setName("non-exist-pipeline");
        req.setId("non-exist-pipeline");
        List<String> idList = new ArrayList<>();
        idList.add("non-exist-pipeline");
        req.setIdList(idList);
        req.setGroupId("1");
        req.setCreator("1");
        req.setCollect(1);

        List<PipelineFindResp> result = pipelineService.findPipelineList(req);

        assertNotNull(result);
        assertTrue(result.isEmpty());
    }

    @Test
    void testDeleteByPipelineId(){
        PipelineReq pipelineReq = new PipelineReq();
        pipelineReq.setId("717383892016959488");

        pipelineService.deletePipeline(pipelineReq);

    }

    @Test
    void testDeleteByPipelineIdNoSuccess(){
        PipelineReq pipelineReq = new PipelineReq();
        pipelineReq.setId("1");

        pipelineService.deletePipeline(pipelineReq);

    }


    @Test
    public void testUpdatePipeline() {
        // 准备测试数据
        PipelineUpdateReq request = new PipelineUpdateReq();
        request.setId("1");
        request.setName("Updated Pipeline Name");

        // 执行方法
        pipelineService.updatePipeline(request);
    }


    /**
     * 测试正常查询流水线列表
     */
    @Test
    void testFindPipelinePage_Normal() {
        PipelineQueryReq req = new PipelineQueryReq();
        req.setName("test-ljc");

        // 验证结果
        PageResult<PipelineFindResp> pipelinePage = pipelineService.findPipelinePage(req);

        assertNotNull(pipelinePage);
        assertFalse(pipelinePage.getList().isEmpty());

        pipelinePage.getList().forEach(p -> {
            assertNotNull(p.getId());
            assertNotNull(p.getName());
            assertNotNull(p.getCreatorName());
        });
    }

    /**
     * 测试无匹配数据时返回空列表
     */
    @Test
    void testFindPipelinePage_EmptyResult() {
        PipelineQueryReq req = new PipelineQueryReq();
        req.setName("non-exist-pipeline");
        req.setId("non-exist-pipeline");
        List<String> idList = new ArrayList<>();
        idList.add("non-exist-pipeline");
        req.setIdList(idList);
        req.setGroupId("1");
        req.setCreator("1");
        req.setCollect(1);

        PageResult<PipelineFindResp> pipelinePage = pipelineService.findPipelinePage(req);

        assertNotNull(pipelinePage);
        assertTrue(pipelinePage.getList().isEmpty());
    }



    @Test
    public void testPipelineClone_WithEmptyIdOrName_ShouldThrowException() {
        PipelineReq req = new PipelineReq();
        req.setId("716293518217318400");
        req.setName("test-ljc-1");

        pipelineService.pipelineClone(req);

//        assertThatThrownBy(() -> )
//                .isInstanceOf(ServiceException.class)
//                .hasFieldOrPropertyWithValue("code", GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode())
//                .hasMessageContaining("参数不能为空");
    }

    @Test
    public void testPipelineClone_WithNonExistentPipeline_ShouldThrowException() {
        PipelineReq req = new PipelineReq();
        req.setId("non-existent-id");
        req.setName("New Pipeline Name");

//        when(pipelineDao.selectById(req.getId())).thenReturn(null);

        assertThatThrownBy(() -> pipelineService.pipelineClone(req))
                .isInstanceOf(ServiceException.class)
                .hasFieldOrPropertyWithValue("code", GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode())
                .hasMessageContaining("数据错误，请联系管理员");
    }


}
