import { preferences, PREFERENCE_FORMAT_VERSION } from "$lib/stores/preferences";
import type { Preferences } from "$lib/stores/preferences";
import { get } from "svelte/store";

export function CheckMigrationStatus() {
    let currentStore = get(preferences);
    if ( currentStore.format == 1 ) {
        const hasOldKeys = 
            localStorage.getItem('ql') !== null ||
            localStorage.getItem('location') !== null ||
            localStorage.getItem('telemetry') !== null;
        
        if (hasOldKeys) {
            migrateToV1()
        }
    }

    // Handle higher current version than supported or unparsable number
    if (
        !currentStore ||
        typeof currentStore.format !== 'number' ||
        currentStore.format > PREFERENCE_FORMAT_VERSION
    ) {
        preferences.reset();
        console.warn('[Migration] Preferences reset due to invalid format version')
        // Re-read store after reset
        currentStore = get(preferences);
    }

    // Loop through required migrations
    while (currentStore.format < PREFERENCE_FORMAT_VERSION) {
        // Future Migration Logic
        /*
        switch (currentStore.format) {
            case 0:
                migrateToV1();
                break;
            
            default:
                console.warn(`[Migration] Unknown format ${currentStore.format}, resetting to default`);
                preferences.reset();
                break;
        }

        // Re-read store after migration
        currentStore = get(preferences);
        */
        break; // Don't forget to remove this!
    }

    
}

// Migrations

function migrateToV1() {
    const oldQlRaw = localStorage.getItem('ql');
    const oldLocationRaw = localStorage.getItem('location');
    const oldTelemetryRaw = localStorage.getItem('telemetry');
    const oldTelemetryRequestedRaw = localStorage.getItem('telemetryRequested');

    const ql: string[] = safeParseJSON(oldQlRaw, []);
    const location: boolean = parseBool(oldLocationRaw, false);
    const telemetry: boolean = parseBool(oldTelemetryRaw, false);
    const telemetryRequested: Date | null = oldTelemetryRequestedRaw === "yes" ? new Date() : null;

    const migrated: Preferences = { ql, location, telemetry, telemetryRequested, format: 1 };

    preferences.set(migrated);

    localStorage.removeItem('ql');
    localStorage.removeItem('location');
    localStorage.removeItem('telemetry');
    localStorage.removeItem('telemetryRequested');

    console.info('[Migration] Preferences migrated to version 1');
}

// Helpers

function safeParseJSON<T>(raw: string | null, fallback: T): T {
    if (!raw) return fallback;
    try {
        return JSON.parse(raw) as T;
    } catch {
        return fallback;
    }
}

function parseBool(raw: string | null, fallback: boolean): boolean {
    if (raw == 'true') return true;
    if (raw == 'false') return false;
    return fallback;
}
