/**
 * IndexedDB-backed storage for NADIPLAYER.
 *
 * Replaces the previous `localStorage.setItem("nadiplay_profiles", JSON.stringify(...))`
 * pattern that quickly hit the ~5 MB browser quota when M3U playlist text or
 * Stalker channel caches were stored on the profile object.
 *
 * We keep a *very small* breadcrumb (the active profile id) in localStorage so
 * the initial render can paint without an async hop, but everything bulky now
 * lives in IndexedDB via Dexie.
 */
import Dexie, { type Table } from "dexie";
import type { XtreamProfile } from "@/types/xtream";

class NadiDB extends Dexie {
  profiles!: Table<XtreamProfile, string>;

  constructor() {
    super("nadiplay");
    this.version(1).stores({
      // Primary key = id. No other indexes needed — list is small (<1000).
      profiles: "id",
    });
  }
}

export const nadiDb = new NadiDB();

// One-time legacy migration: copy existing localStorage profiles into Dexie
// so users don't lose anything, then clear the (potentially over-quota) key.
const LEGACY_KEY = "nadiplay_profiles";
const MIGRATED_KEY = "nadiplay_profiles_migrated_v1";

export const migrateLegacyProfiles = async (): Promise<void> => {
  try {
    if (localStorage.getItem(MIGRATED_KEY) === "1") return;
    const raw = localStorage.getItem(LEGACY_KEY);
    if (raw) {
      try {
        const parsed = JSON.parse(raw) as XtreamProfile[];
        if (Array.isArray(parsed) && parsed.length) {
          await nadiDb.profiles.bulkPut(parsed);
        }
      } catch {
        /* ignore corrupt legacy data */
      }
      // Always clear the legacy bucket — it's the source of QuotaExceededError.
      localStorage.removeItem(LEGACY_KEY);
    }
    localStorage.setItem(MIGRATED_KEY, "1");
  } catch {
    /* localStorage / IDB might be disabled (private mode, etc.) — give up
       quietly; the app will still work, just without persistence. */
  }
};
