package com.ruoyi.ccdi.project.mapper;

import org.junit.jupiter.api.Test;

import java.nio.file.Files;
import java.nio.file.Path;

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

class CcdiProjectMapperXmlTest {

    @Test
    void projectQueriesShouldApplyProjectVisibilityAndDeletedFilters() throws Exception {
        String xml = Files.readString(Path.of("src/main/resources/mapper/ccdi/project/CcdiProjectMapper.xml"));

        assertFalse(xml.contains("params.dataScope"), xml);
        assertFalse(xml.contains("${queryDTO.params.dataScope}"), xml);

        String listSql = extractSelect(xml, "selectProjectPage");
        assertTrue(listSql.contains("LEFT JOIN sys_user u ON p.create_by = u.user_name"), listSql);
        assertTrue(listSql.contains("scope != null and !scope.viewAllProjects"), listSql);
        assertTrue(listSql.contains("p.create_by = #{scope.username}"), listSql);
        assertTrue(listSql.contains("queryDTO.includeDeleted"), listSql);
        assertTrue(listSql.contains("p.del_flag = '2'"), listSql);
        assertTrue(listSql.contains("p.status = '5'"), listSql);
        assertTrue(listSql.contains("p.del_flag = '0'"), listSql);
        assertTrue(listSql.contains("p.status != '5'"), listSql);

        String historySql = extractSelect(xml, "selectHistoryProjects");
        assertTrue(historySql.contains("p.status in ('1', '2')"), historySql);
        assertTrue(historySql.contains("p.del_flag = '0'"), historySql);

        assertTrue(xml.contains("<update id=\"markProjectDeleted\">"), xml);
        assertTrue(xml.contains("status = '5'"), xml);
        assertTrue(xml.contains("del_flag = '2'"), xml);
        assertTrue(xml.contains("<update id=\"restoreDeletedProject\">"), xml);
        assertTrue(xml.contains("status = '1'"), xml);
        assertTrue(xml.contains("del_flag = '0'"), xml);
        assertTrue(xml.contains("is_archived = 0"), xml);
    }

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