package thb.jeanluc.adventure.save;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import thb.jeanluc.adventure.io.ConsoleIO;
import thb.jeanluc.adventure.io.MusicLevel;

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

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

class SettingsStoreTest {

    @Test
    void savesAndLoads(@TempDir Path dir) {
        SettingsStore store = new SettingsStore(dir.resolve("settings.json"));
        store.save(new Settings(ConsoleIO.ColorMode.ON, ConsoleIO.GlyphMode.ASCII));
        Settings loaded = store.load();
        assertThat(loaded.colorMode()).isEqualTo(ConsoleIO.ColorMode.ON);
        assertThat(loaded.glyphMode()).isEqualTo(ConsoleIO.GlyphMode.ASCII);
        assertThat(loaded.musicLevel()).isEqualTo(MusicLevel.MEDIUM);
    }

    @Test
    void missingFileReturnsDefaults(@TempDir Path dir) {
        Settings loaded = new SettingsStore(dir.resolve("nope.json")).load();
        assertThat(loaded).isEqualTo(Settings.defaults());
    }

    @Test
    void corruptFileReturnsDefaults(@TempDir Path dir) throws IOException {
        Path file = dir.resolve("settings.json");
        Files.writeString(file, "{ not json");
        Settings loaded = new SettingsStore(file).load();
        assertThat(loaded).isEqualTo(Settings.defaults());
    }

    @Test
    void musicLevelRoundTrips(@TempDir Path dir) {
        SettingsStore store = new SettingsStore(dir.resolve("settings.json"));
        store.save(new Settings(ConsoleIO.ColorMode.AUTO, ConsoleIO.GlyphMode.UNICODE, MusicLevel.HIGH));
        assertThat(store.load().musicLevel()).isEqualTo(MusicLevel.HIGH);
    }

    @Test
    void oldSettingsWithoutMusicDefaultToMedium(@TempDir Path dir) throws Exception {
        Path file = dir.resolve("settings.json");
        Files.writeString(file, "{\"colorMode\":\"ON\",\"glyphMode\":\"ASCII\"}");
        assertThat(new SettingsStore(file).load().musicLevel()).isEqualTo(MusicLevel.MEDIUM);
    }
}
