package com.ruoyi.ccdi.project.mapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

class CcdiProjectSpecialCheckExtendedPurchaseSqlTest {

    @Test
    void shouldExposeExtendedPurchaseMapperMethodsAndSqlCaliber() throws Exception {
        Class<?> mapperClass = Class.forName("com.ruoyi.ccdi.project.mapper.CcdiProjectSpecialCheckMapper");
        Class<?> queryClass = Class.forName("com.ruoyi.ccdi.project.domain.dto.CcdiProjectExtendedPurchaseQueryDTO");

        Method listMethod = mapperClass.getMethod("selectExtendedPurchasePage", Page.class, queryClass);
        Method detailMethod = mapperClass.getMethod("selectExtendedPurchaseDetail", Long.class, String.class);
        assertEquals("Page", listMethod.getReturnType().getSimpleName());
        assertEquals("CcdiProjectExtendedPurchaseDetailVO", detailMethod.getReturnType().getSimpleName());

        String xml = Files.readString(Path.of("src/main/resources/mapper/ccdi/project/CcdiProjectSpecialCheckMapper.xml"));
        String listSql = extractSelect(xml, "selectExtendedPurchasePage");
        String detailSql = extractSelect(xml, "selectExtendedPurchaseDetail");

        assertTrue(listSql.contains("projectEmployeeScopeSql"));
        assertTrue(listSql.contains("name=\"projectId\" value=\"query.projectId\""));
        assertTrue(listSql.contains("select distinct scope.staff_name"));
        assertTrue(listSql.contains("applicant_name"));
        assertTrue(listSql.contains("apply_date"));
        assertTrue(listSql.contains("purchase_id"));
        assertTrue(listSql.contains("project_name"));
        assertTrue(listSql.contains("subject_name"));
        assertTrue(listSql.contains("order by p.apply_date desc, p.create_time desc, p.purchase_id desc"));
        assertTrue(detailSql.contains("projectEmployeeScopeSql"));
        assertTrue(detailSql.contains("purchase_id = #{purchaseId}"));
        assertTrue(detailSql.contains("applicant_name"));
    }

    private String extractSelect(String xml, String selectId) {
        String start = "<select id=\"" + selectId + "\"";
        int startIndex = xml.indexOf(start);
        int endIndex = xml.indexOf("</select>", startIndex);
        return xml.substring(startIndex, endIndex);
    }
}
