package com.ruoyi.generator.service.front;

import static org.junit.Assert.assertTrue;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;

public class FrontProjectSchemaScriptTest
{
    private static final String[] FRONT_PROJECT_DRAFT_COLUMNS = {
            "requirement_keyword",
            "industry_template",
            "frontend_enabled",
            "app_blueprint",
            "er_diagram",
            "business_blueprint"
    };

    @Test
    public void upgradeScriptBackfillsMappedFrontProjectDraftColumns() throws Exception
    {
        Path repoRoot = repoRoot();
        String mapperXml = read(repoRoot.resolve("ruoyi-generator/src/main/resources/mapper/front/FrontProjectMapper.xml"));
        String upgradeSql = read(repoRoot.resolve("sql/front_project_upgrade.sql")).toLowerCase();

        for (String column : FRONT_PROJECT_DRAFT_COLUMNS)
        {
            assertTrue("FrontProjectMapper should map " + column, mapperXml.contains(column));
            assertTrue("front_project_upgrade.sql should check " + column,
                    upgradeSql.contains("column_name = '" + column + "'"));
            assertTrue("front_project_upgrade.sql should add " + column,
                    upgradeSql.contains("add column " + column));
        }
        assertTrue("front_project_upgrade.sql should create front_project_module",
                upgradeSql.contains("create table if not exists front_project_module"));
        assertTrue("front_workbench.sql should create front_project_module",
                read(repoRoot.resolve("sql/front_workbench.sql")).contains("create table front_project_module"));
    }

    @Test
    public void dbSqlIncludesBusinessBlueprintTemplates() throws Exception
    {
        String dbSql = read(repoRoot().resolve("sql/db.sql"));

        assertTrue("db.sql should include business blueprint backend template",
                dbSql.contains("Business Blueprint Backend"));
        assertTrue("db.sql should include executable blueprint effects",
                dbSql.contains("executeUpdateFieldEffect"));
        assertTrue("db.sql should include frontend menu template",
                dbSql.contains("frontendMenus.js.vm"));
    }

    private Path repoRoot()
    {
        Path cwd = Paths.get("").toAbsolutePath();
        if ("ruoyi-generator".equals(cwd.getFileName().toString()))
        {
            return cwd.getParent();
        }
        return cwd;
    }

    private String read(Path path) throws Exception
    {
        return new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
    }
}
