"use strict";

async function exportVendorGetEvidenceJson() {
  const db = await openVendorGetDb();
  const storeNames = [...VENDORGET_EVIDENCE_STORE_NAMES];
  const stores = await exportVendorGetEvidenceStores(db, storeNames);
  const summary = buildVendorGetEvidenceExportSummary(stores);

  return {
    metadata: {
      exportVersion: 1,
      exportedAt: new Date().toISOString(),
      project: "VG-Environment",
      extension: "VendorGet",
      dbName: db.name,
      dbVersion: db.version,
      stores: storeNames,
      summary
    },
    stores
  };
}

function buildVendorGetEvidenceExportSummary(stores) {
  const storeRecordCounts = {};
  let totalRecordCount = 0;

  for (const [storeName, storeExport] of Object.entries(stores)) {
    const recordCount = storeExport.recordCount;

    storeRecordCounts[storeName] = recordCount;
    totalRecordCount += recordCount;
  }

  return {
    totalRecordCount,
    storeRecordCounts
  };
}

function exportVendorGetEvidenceStores(db, storeNames) {
  return new Promise((resolve, reject) => {
    const stores = {};
    const tx = db.transaction(storeNames, "readonly");

    tx.onerror = () => reject(tx.error);
    tx.onabort = () => reject(tx.error);
    tx.oncomplete = () => resolve(stores);

    for (const storeName of storeNames) {
      const objectStore = tx.objectStore(storeName);
      const storeExport = {
        keyPath: objectStore.keyPath,
        autoIncrement: objectStore.autoIncrement,
        recordCount: 0,
        records: []
      };

      stores[storeName] = storeExport;

      const cursorRequest = objectStore.openCursor();

      cursorRequest.onerror = () => reject(cursorRequest.error);
      cursorRequest.onsuccess = () => {
        const cursor = cursorRequest.result;

        if (!cursor) {
          return;
        }

        storeExport.records.push({
          key: cursor.key,
          value: cursor.value
        });
        storeExport.recordCount += 1;
        cursor.continue();
      };
    }
  });
}
