package dev.photosync.core.config;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

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

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

/** The marker that decides where the settings file lives. */
class ConfigLocationsTest {

    @TempDir
    Path temp;

    @Test
    void resolvesTheInstanceDirectoryWhenThereIsNoMarker() {
        ConfigLocations locations = new ConfigLocations(temp.resolve("instance"), temp.resolve("user"));
        assertEquals(ConfigLocation.INSTANCE, locations.resolve());
        assertEquals(temp.resolve("instance"), locations.directory(ConfigLocation.INSTANCE));
        assertEquals(temp.resolve("user"), locations.directory(ConfigLocation.USER));
    }

    @Test
    void remembersTheChoiceAcrossInstances() throws Exception {
        Path instance = temp.resolve("instance");
        ConfigLocations locations = new ConfigLocations(instance, temp.resolve("user"));
        locations.writeMarker(ConfigLocation.USER);

        // A fresh PhotoSync reads the same marker and arrives at the same answer.
        ConfigLocations reopened = new ConfigLocations(instance, temp.resolve("user"));
        assertEquals(ConfigLocation.USER, reopened.resolve());
    }

    @Test
    void fallsBackToTheInstanceDirectoryForAGarbageMarker() throws Exception {
        Path instance = temp.resolve("instance");
        Files.createDirectories(instance);
        Files.writeString(instance.resolve("location.json"), "not json");

        ConfigLocations locations = new ConfigLocations(instance, temp.resolve("user"));
        assertEquals(ConfigLocation.INSTANCE, locations.resolve());
    }

    @Test
    void fallsBackToTheInstanceDirectoryForAnUnknownLocation() throws Exception {
        Path instance = temp.resolve("instance");
        Files.createDirectories(instance);
        Files.writeString(instance.resolve("location.json"), "{\"location\":\"elsewhere\"}");

        ConfigLocations locations = new ConfigLocations(instance, temp.resolve("user"));
        assertEquals(ConfigLocation.INSTANCE, locations.resolve());
    }

    @Test
    void fixedCatalogTreatsTheUserDirectoryAsTheInstanceDirectory() {
        ConfigLocations locations = ConfigLocations.fixed(temp.resolve("dir"));
        assertEquals(ConfigLocation.INSTANCE, locations.resolve());
        assertEquals(locations.directory(ConfigLocation.INSTANCE), locations.directory(ConfigLocation.USER));
    }
}
