package p.studio.controls.shell;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.studio.projects.ProjectReference;
import p.studio.projects.ProjectStudioPaths;

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

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

final class StudioActivityStorageServiceTest {
    @TempDir
    Path tempDir;

    @Test
    void savesAndLoadsProjectScopedActivityHistory() throws Exception {
        final StudioActivityStorageService service = new StudioActivityStorageService();
        final ProjectReference project = project("main");
        final List<StudioActivityEntry> history = List.of(
                new StudioActivityEntry("Studio", "Project opened", StudioActivityEntrySeverity.SUCCESS, false),
                new StudioActivityEntry("Assets", "3 assets loaded", StudioActivityEntrySeverity.INFO, false));

        service.save(project, history);

        assertTrue(Files.isRegularFile(ProjectStudioPaths.activitiesPath(project)));
        assertEquals(history, service.load(project));
    }

    @Test
    void trimsPersistedHistoryToConfiguredMaximum() {
        final StudioActivityStorageService service = new StudioActivityStorageService();
        final ProjectReference project = project("main");
        final List<StudioActivityEntry> history = new ArrayList<>();
        for (int index = 0; index < StudioActivityStorageService.MAX_HISTORY + 25; index += 1) {
            history.add(new StudioActivityEntry(
                    "Assets",
                    "Entry " + index,
                    StudioActivityEntrySeverity.INFO,
                    false));
        }

        service.save(project, history);

        final List<StudioActivityEntry> loaded = service.load(project);
        assertEquals(StudioActivityStorageService.MAX_HISTORY, loaded.size());
        assertEquals("Entry 0", loaded.getFirst().message());
        assertEquals("Entry 499", loaded.getLast().message());
    }

    @Test
    void malformedStorageFallsBackToEmptyHistory() throws Exception {
        final StudioActivityStorageService service = new StudioActivityStorageService();
        final ProjectReference project = project("main");
        Files.createDirectories(ProjectStudioPaths.studioRoot(project));
        Files.writeString(ProjectStudioPaths.activitiesPath(project), "{ not valid json");

        assertEquals(List.of(), service.load(project));
    }

    private ProjectReference project(String name) {
        final Path projectRoot = tempDir.resolve(name);
        return new ProjectReference("Main", "1.0.0", "pbs", 1, projectRoot);
    }
}
