package click.kamil.springstatemachineexporter.analysis.service;

import click.kamil.springstatemachineexporter.analysis.model.LifecycleTriggerMarkers;
import click.kamil.springstatemachineexporter.analysis.model.TriggerPoint;
import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

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

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

class LifecycleDetectorTest {

    @Test
    void shouldDetectPersisterRestoreCalls(@TempDir Path tempDir) throws Exception {
        String source = """
            package com.example;
            import org.springframework.statemachine.StateMachine;
            import org.springframework.statemachine.persist.StateMachinePersister;
            public class OrderService {
                private final StateMachine<String, String> stateMachine;
                private final StateMachinePersister<String, String, String> persister;
                OrderService(StateMachine<String, String> sm, StateMachinePersister<String, String, String> p) {
                    this.stateMachine = sm;
                    this.persister = p;
                }
                public void resume(String id) throws Exception {
                    persister.restore(stateMachine, id);
                }
            }
            """;
        Files.writeString(tempDir.resolve("OrderService.java"), source);

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

        LifecycleDetector detector = new LifecycleDetector(context);
        org.eclipse.jdt.core.dom.TypeDeclaration td = context.getTypeDeclaration("com.example.OrderService");
        org.eclipse.jdt.core.dom.CompilationUnit cu =
                (org.eclipse.jdt.core.dom.CompilationUnit) td.getRoot();

        List<TriggerPoint> triggers = detector.detect(cu);
        assertThat(triggers).hasSize(1);
        assertThat(triggers.get(0).getEvent()).isEqualTo("[LIFECYCLE:RESTORE]");
        assertThat(triggers.get(0).getMethodName()).isEqualTo("resume");
        assertThat(LifecycleTriggerMarkers.lifecycleType(triggers.get(0).getEvent())).isEqualTo("RESTORE");
    }
}
