package cn.qg.qaplatform.automation.service.impl;

import cn.qg.qaplatform.automation.domain.Assertion;
import cn.qg.qaplatform.automation.mapper.AssertionMapper;
import cn.qg.qaplatform.automation.service.AssertService;
import cn.qg.qaplatform.utils.assertion.assertUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AssertServiceImpl extends ServiceImpl<AssertionMapper, Assertion> implements AssertService {

    @Autowired
    AssertionMapper assertionMapper;

    @Override
    public Boolean assertResponse(Integer testcaseId, JSONObject response) {
        QueryWrapper<Assertion> assertionQueryWrapper = new QueryWrapper<>();
        assertionQueryWrapper.eq("testcase_id", testcaseId);
        List<Assertion> assertionList = assertionMapper.selectList(assertionQueryWrapper);
        if (assertionList != null) {
            for (Assertion assertion: assertionList) {
                Boolean assertResult = assertUtil.assertJsonResponse(response, assertion.getComparator(), assertion.getPath(), assertion.getExpect());
                if (!assertResult) {
                    log.info("断言失败，本次断言的内容为，对比符：" + assertion.getComparator() + "，检查项：" + assertion.getPath() + "，期望值：" + assertion.getExpect());
                    return false;
                }
            }
        }
        return true;
    }
}
