// Database: ninja (IndexedDB)
// Object Stores: agents
// CRUD helpers for agents: add, getAll, getById, update, delete

const DB_NAME = 'ninja';
const DB_VERSION = 1;
const STORE_AGENTS = 'agents';

function openDB() {
  return new Promise((resolve, reject) => {
    const request = window.indexedDB.open(DB_NAME, DB_VERSION);

    request.onupgradeneeded = function (event) {
      const db = event.target.result;
      if (!db.objectStoreNames.contains(STORE_AGENTS)) {
        const store = db.createObjectStore(STORE_AGENTS, { keyPath: 'id', autoIncrement: true });
        store.createIndex('agent_name', 'agent_name', { unique: false });
        store.createIndex('email', 'email', { unique: false });
      }
    };

    request.onsuccess = function () {
      resolve(request.result);
    };
    request.onerror = function () {
      reject(request.error);
    };
  });
}

function tx(db, storeName, mode = 'readonly') {
  const t = db.transaction(storeName, mode);
  return t.objectStore(storeName);
}

export async function addAgent(agent) {
  const db = await openDB();
  return new Promise((resolve, reject) => {
    const store = tx(db, STORE_AGENTS, 'readwrite');
    const data = { ...agent, created_at: new Date().toISOString() };
    const req = store.add(data);
    req.onsuccess = function () {
      resolve(req.result);
    };
    req.onerror = function () {
      reject(req.error);
    };
  });
}

export async function getAllAgents() {
  const db = await openDB();
  return new Promise((resolve, reject) => {
    const store = tx(db, STORE_AGENTS, 'readonly');
    const req = store.getAll();
    req.onsuccess = function () {
      resolve(req.result);
    };
    req.onerror = function () {
      reject(req.error);
    };
  });
}

export async function getAgent(id) {
  const db = await openDB();
  return new Promise((resolve, reject) => {
    const store = tx(db, STORE_AGENTS, 'readonly');
    const req = store.get(Number(id));
    req.onsuccess = function () {
      resolve(req.result || null);
    };
    req.onerror = function () {
      reject(req.error);
    };
  });
}

export async function updateAgent(id, updates) {
  const db = await openDB();
  return new Promise(async (resolve, reject) => {
    try {
      const store = tx(db, STORE_AGENTS, 'readwrite');
      const currentReq = store.get(Number(id));
      currentReq.onsuccess = function () {
        const existing = currentReq.result;
        if (!existing) {
          reject(new Error('Agent not found'));
          return;
        }
        const updated = { ...existing, ...updates, updated_at: new Date().toISOString() };
        const putReq = store.put(updated);
        putReq.onsuccess = function () {
          resolve(putReq.result);
        };
        putReq.onerror = function () {
          reject(putReq.error);
        };
      };
      currentReq.onerror = function () {
        reject(currentReq.error);
      };
    } catch (e) {
      reject(e);
    }
  });
}

export async function deleteAgent(id) {
  const db = await openDB();
  return new Promise((resolve, reject) => {
    const store = tx(db, STORE_AGENTS, 'readwrite');
    const req = store.delete(Number(id));
    req.onsuccess = function () {
      resolve(true);
    };
    req.onerror = function () {
      reject(req.error);
    };
  });
}

export function parseQuery() {
  const params = new URLSearchParams(window.location.search);
  const out = {};
  for (const [k, v] of params.entries()) out[k] = v;
  return out;
}
