package p.studio.compiler.pbs.stdlib;

import org.junit.jupiter.api.Test;
import p.studio.compiler.models.ProjectDescriptor;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.tables.FileTable;
import p.studio.compiler.source.tables.ProjectTable;
import p.studio.utilities.structures.ReadOnlyList;

import java.nio.file.Path;

import static org.junit.jupiter.api.Assertions.*;

class InterfaceModuleLoaderTest {

    @Test
    void shouldRegisterSyntheticStdlibFilesInFileTable() {
        final var projectTable = new ProjectTable();
        final var projectId = projectTable.register(ProjectDescriptor.builder()
                .name("app")
                .version("1.0.0")
                .rootPath(Path.of("/tmp/app"))
                .sourceRoots(ReadOnlyList.wrap(java.util.List.of(Path.of("/tmp/app/src"))))
                .build());
        final var fileTable = new FileTable(1);
        final var diagnostics = DiagnosticSink.empty();
        final var moduleSource = new StdlibModuleSource(
                "sdk",
                ReadOnlyList.wrap(java.util.List.of("gfx")),
                ReadOnlyList.wrap(java.util.List.of(new StdlibModuleSource.SourceFile(
                        "source.pbs",
                        "declare host Gfx { fn draw() -> void; }"))),
                "pub host Gfx;");

        final var module = new InterfaceModuleLoader().load(moduleSource, projectId, fileTable, diagnostics);

        assertTrue(diagnostics.isEmpty());
        assertEquals(1, module.sourceFiles().size());
        assertEquals(1, module.barrelFiles().size());
        assertFalse(module.sourceFiles().getFirst().fileId().isNone());
        assertFalse(module.barrelFiles().getFirst().fileId().isNone());
        assertTrue(fileTable.get(module.sourceFiles().getFirst().fileId()).readUtf8().isPresent());
        assertTrue(fileTable.get(module.barrelFiles().getFirst().fileId()).readUtf8().isPresent());
        assertEquals(
                "declare host Gfx { fn draw() -> void; }",
                fileTable.get(module.sourceFiles().getFirst().fileId()).readUtf8().orElseThrow());
        assertEquals(
                "pub host Gfx;",
                fileTable.get(module.barrelFiles().getFirst().fileId()).readUtf8().orElseThrow());
    }
}
