package com.ruoyi.generator.service.front;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import org.junit.Test;
import com.ruoyi.generator.domain.front.dto.DatabaseColumnDesign;
import com.ruoyi.generator.domain.front.dto.DatabaseTableDesign;

public class MysqlDdlBuilderTest
{
    private final MysqlDdlBuilder builder = new MysqlDdlBuilder();

    @Test
    public void buildsCreateTableSqlWithPrimaryKeyNullabilityAndEscapedComments()
    {
        DatabaseTableDesign table = new DatabaseTableDesign();
        table.setTableName("car_info");
        table.setTableComment("车辆'信息表");
        table.setColumns(Arrays.asList(
                column("car_id", "bigint(20)", "1", "1", "1", "车辆ID"),
                column("car_no", "varchar(30)", "0", "0", "1", "车牌号"),
                column("remark", "text", "0", "0", "0", "备注'信息")));

        String sql = builder.build(table);

        assertTrue(sql.contains("CREATE TABLE `car_info`"));
        assertTrue(sql.contains("`car_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '车辆ID'"));
        assertTrue(sql.contains("`car_no` varchar(30) NOT NULL COMMENT '车牌号'"));
        assertTrue(sql.contains("`remark` text DEFAULT NULL COMMENT '备注''信息'"));
        assertTrue(sql.contains("PRIMARY KEY (`car_id`)"));
        assertTrue(sql.endsWith("COMMENT='车辆''信息表';"));
    }

    @Test
    public void escapesBackslashQuoteSequencesInsideComments()
    {
        DatabaseTableDesign table = new DatabaseTableDesign();
        table.setTableName("car_info");
        table.setTableComment("safe \\'; update front_project set project_name='owned'");
        table.setColumns(Arrays.asList(
                column("car_id", "bigint(20)", "1", "1", "1", "safe \\'; update front_project set project_name='owned'")));

        String sql = builder.build(table);

        assertFalse(sql.contains("\\'; update"));
        assertTrue(sql.contains("COMMENT 'safe \\\\''; update front_project set project_name=''owned'''"));
        assertTrue(sql.endsWith("COMMENT='safe \\\\''; update front_project set project_name=''owned''';"));
    }

    private DatabaseColumnDesign column(String name, String type, String isPk, String isIncrement,
            String isRequired, String comment)
    {
        DatabaseColumnDesign column = new DatabaseColumnDesign();
        column.setColumnName(name);
        column.setColumnType(type);
        column.setIsPk(isPk);
        column.setIsIncrement(isIncrement);
        column.setIsRequired(isRequired);
        column.setColumnComment(comment);
        return column;
    }
}
