import { CheckMigrationStatus } from "$lib/scripts/migrations/preferencesMigrations";
import { writable } from "svelte/store";

export const PREFERENCE_FORMAT_VERSION = 1;

export interface Preferences {
    ql: string[];
    location: boolean;
    telemetry: boolean;
    telemetryRequested: Date | null;
    format: number;
}

const STORAGE_KEY = 'preferences';

const DEFAULT_PREFERENCES: Preferences = {
    ql: [],
    location: false,
    telemetry: false,
    telemetryRequested: null,
    format: PREFERENCE_FORMAT_VERSION,
};

function createPreferencesStore() {
    let stored: Preferences;
    try {
        const json = localStorage.getItem(STORAGE_KEY);
        stored = json ? JSON.parse(json) : DEFAULT_PREFERENCES;
    } catch {
        stored = DEFAULT_PREFERENCES;
    }

    const { subscribe, set, update } = writable<Preferences>(stored);

    subscribe((value) => {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(value));
    });

    return {
        subscribe,
        set,
        update,
        reset: () => set(DEFAULT_PREFERENCES)
    }
}

export const preferences = createPreferencesStore();
try {
    CheckMigrationStatus();
} catch (e) {
    console.error("Preferences migration failed, resetting store", e);
    preferences.reset();
}
