const DB_NAME = "costco-upload-queue";
const DB_VERSION = 1;
const STORE_NAME = "uploads";

function openUploadQueueDb() {
  return new Promise((resolve, reject) => {
    if (typeof indexedDB === "undefined") {
      reject(new Error("IndexedDB is not available"));
      return;
    }

    const request = indexedDB.open(DB_NAME, DB_VERSION);

    request.onupgradeneeded = () => {
      const db = request.result;
      if (!db.objectStoreNames.contains(STORE_NAME)) {
        db.createObjectStore(STORE_NAME, { keyPath: "id" });
      }
    };

    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error || new Error("Failed to open upload DB"));
  });
}

function withStore(mode, handler) {
  return openUploadQueueDb().then(
    (db) =>
      new Promise((resolve, reject) => {
        const tx = db.transaction(STORE_NAME, mode);
        const store = tx.objectStore(STORE_NAME);
        const request = handler(store);

        tx.oncomplete = () => {
          db.close();
          resolve(request?.result);
        };
        tx.onerror = () => {
          db.close();
          reject(tx.error || new Error("IndexedDB transaction failed"));
        };
      })
  );
}

export function getAllUploadJobs() {
  return withStore("readonly", (store) => store.getAll()).then((rows) =>
    Array.isArray(rows) ? rows : []
  );
}

export function saveUploadJob(job) {
  return withStore("readwrite", (store) => store.put(job));
}

export function deleteUploadJob(id) {
  return withStore("readwrite", (store) => store.delete(id));
}
