package click.kamil.springstatemachineexporter.ast.common;

import click.kamil.springstatemachineexporter.analysis.resolver.ConstantResolver;
import click.kamil.springstatemachineexporter.analysis.service.VariableTracer;
import org.eclipse.jdt.core.dom.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

class LegacyDataFlowModelTest {

    @Test
    void testLegacyDataFlowResolution(@TempDir Path tempDir) throws IOException {
        Path comFoo = tempDir.resolve("com/foo");
        Files.createDirectories(comFoo);
        Files.writeString(comFoo.resolve("Test.java"),
            "package com.foo;\n" +
            "public class Test {\n" +
            "    public void run() {\n" +
            "        String a = \"VAL1\";\n" +
            "        String b = a;\n" +
            "    }\n" +
            "}"
        );

        CodebaseContext context = new CodebaseContext();
        context.scan(tempDir);

        TypeDeclaration td = context.getTypeDeclaration("com.foo.Test");
        assertThat(td).isNotNull();

        MethodDeclaration md = td.getMethods()[0];
        VariableDeclarationStatement bStmt = (VariableDeclarationStatement) md.getBody().statements().get(1);
        VariableDeclarationFragment frag = (VariableDeclarationFragment) bStmt.fragments().get(0);
        Expression initializer = frag.getInitializer(); // 'a' reference

        VariableTracer tracer = new VariableTracer(context, new ConstantResolver());
        DataFlowModel model = new LegacyDataFlowModel(tracer);

        List<Expression> defs = model.getReachingDefinitions(initializer);
        assertThat(defs).isNotEmpty();
        
        Expression resolvedExpr = defs.get(defs.size() - 1);
        assertThat(resolvedExpr).isInstanceOf(StringLiteral.class);
        assertThat(((StringLiteral) resolvedExpr).getLiteralValue()).isEqualTo("VAL1");

        String val = model.resolveValue(initializer, context);
        assertThat(val).isEqualTo("VAL1");
    }
}
