"use strict";

async function lockAllEvidenceRecords(reason, note) {
  const db = await openVendorGetDb();
  const lockedAt = new Date().toISOString();
  const recordLockReason = reason ?? "dsar_used";
  const recordLockNote = note ?? null;

  return updateAllEvidenceRecords((record) => ({
    ...record,
    bolRecordLock: true,
    recordLockReason,
    recordLockedAt: lockedAt,
    recordLockNote
  }), "lockedCount", db);
}

async function unlockAllEvidenceRecords() {
  const db = await openVendorGetDb();
  const unlockedAt = new Date().toISOString();

  return updateAllEvidenceRecords((record) => ({
    ...record,
    bolRecordLock: false,
    recordLockReason: null,
    recordLockNote: null,
    recordLockedAt: null,
    recordUnlockedAt: unlockedAt
  }), "unlockedCount", db);
}

function updateAllEvidenceRecords(buildUpdatedRecord, countKey, db) {
  return new Promise((resolve, reject) => {
    let updatedCount = 0;
    const tx = db.transaction(VENDORGET_EVIDENCE_STORE_NAMES, "readwrite");

    tx.onerror = () => reject(tx.error);
    tx.onabort = () => reject(tx.error);
    tx.oncomplete = () => {
      resolve({
        success: true,
        [countKey]: updatedCount
      });
    };

    for (const storeName of VENDORGET_EVIDENCE_STORE_NAMES) {
      const cursorRequest = tx.objectStore(storeName).openCursor();

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

        if (!cursor) {
          return;
        }

        const updateRequest = cursor.update(buildUpdatedRecord(cursor.value));
        updateRequest.onerror = () => {
          reject(updateRequest.error);
        };
        updateRequest.onsuccess = () => {
          updatedCount += 1;
          cursor.continue();
        };
      };
    }
  });
}
