package com.graphtest;

import com.graphtest.model.Edge;
import com.graphtest.model.NodeStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

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

@DisplayName("Case 4: Self-Reference (A → A)")
class Case4_SelfReferenceTest {

    private CodeGraph graph;

    @BeforeEach
    void setUp() throws Exception {
        URL resource = getClass().getClassLoader().getResource("fixtures/case4_self_reference");
        Path dir = Paths.get(resource.toURI());
        graph = new GraphBuilder().buildFromDirectory(dir);
    }

    @Test
    @DisplayName("Graph phải build thành công, không bị infinite loop")
    void graphShouldBuildWithoutInfiniteLoop() {
        assertThat(graph).isNotNull();
        assertThat(graph.hasNode("SelfRef")).isTrue();
    }

    @Test
    @DisplayName("Node SelfRef phải có status OK")
    void selfRefNodeShouldHaveOkStatus() {
        assertThat(graph.getNode("SelfRef").getStatus()).isEqualTo(NodeStatus.OK);
    }

    @Test
    @DisplayName("Self-loop edge phải được phát hiện")
    void selfLoopEdgeShouldBeDetected() {
        assertThat(graph.getSelfLoops()).isNotEmpty();
    }

    @Test
    @DisplayName("Self-loop phải là SelfRef → SelfRef")
    void selfLoopShouldPointToItself() {
        List<Edge> selfLoops = graph.getSelfLoops();
        assertThat(selfLoops).anyMatch(e ->
            e.getSource().getClassName().equals("SelfRef") &&
            e.getTarget().getClassName().equals("SelfRef") &&
            e.isSelfLoop());
    }

    @Test
    @DisplayName("Graph không tạo node trùng lặp cho self-reference")
    void shouldNotCreateDuplicateNode() {
        assertThat(graph.getNodes()).hasSize(1);
    }

    @Test
    @DisplayName("Self-reference không gây build error")
    void selfReferenceShouldNotCauseBuildError() {
        assertThat(graph.getBuildErrors()).isEmpty();
    }
}
