package click.kamil.springstatemachineexporter.analysis.service;

import click.kamil.springstatemachineexporter.analysis.model.TriggerPoint;
import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
import lombok.RequiredArgsConstructor;
import org.eclipse.jdt.core.dom.*;

import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
public class LifecycleDetector {
    private final CodebaseContext context;

    public List<TriggerPoint> detect(CompilationUnit cu) {
        List<TriggerPoint> lifecyclePoints = new ArrayList<>();
        cu.accept(new ASTVisitor() {
            @Override
            public boolean visit(MethodInvocation node) {
                String methodName = node.getName().getIdentifier();
                if ("restore".equals(methodName) || "reset".equals(methodName)) {
                    TriggerPoint point = buildLifecyclePoint(node, cu, methodName);
                    if (point != null) {
                        lifecyclePoints.add(point);
                    }
                }
                return super.visit(node);
            }
        });
        return lifecyclePoints;
    }

    private TriggerPoint buildLifecyclePoint(MethodInvocation node, CompilationUnit cu, String type) {
        MethodDeclaration method = click.kamil.springstatemachineexporter.ast.common.AstUtils.findEnclosingMethod(node);
        TypeDeclaration typeDecl = click.kamil.springstatemachineexporter.ast.common.AstUtils.findEnclosingType(node);

        if (typeDecl == null) return null;

        return TriggerPoint.builder()
                .event("[LIFECYCLE:" + type.toUpperCase() + "]")
                .className(context.getFqn(typeDecl))
                .methodName(method != null ? method.getName().getIdentifier() : "initializer")
                .lineNumber(cu.getLineNumber(node.getStartPosition()))
                .build();
    }
}
