/* global indexedDB */

const CatalogStore = (() => {
  const DB_NAME = "viral-tension-streaming";
  const DB_VERSION = 1;
  const SONGS = "songs";

  const openDb = () => new Promise((resolve, reject) => {
    const req = indexedDB.open(DB_NAME, DB_VERSION);
    req.onupgradeneeded = () => {
      const db = req.result;
      if (!db.objectStoreNames.contains(SONGS)) {
        db.createObjectStore(SONGS, { keyPath: "id" });
      }
    };
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  });

  const txStore = async (mode = "readonly") => {
    const db = await openDb();
    const tx = db.transaction(SONGS, mode);
    return { db, tx, store: tx.objectStore(SONGS) };
  };

  const request = (req) => new Promise((resolve, reject) => {
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  });

  const listSongs = async () => {
    const { db, store } = await txStore();
    try {
      return await request(store.getAll());
    } finally {
      db.close();
    }
  };

  const addSong = async (song) => {
    const saved = {
      ...song,
      id: song.id || `uploaded-${Date.now()}`,
      source: "uploaded",
      createdAt: new Date().toISOString(),
    };
    const { db, store } = await txStore("readwrite");
    try {
      await request(store.put(saved));
      return saved;
    } finally {
      db.close();
    }
  };

  return { listSongs, addSong };
})();

window.CatalogStore = CatalogStore;
