// VERA Vault — Service Worker (Background Script)
// Handles: credential storage, proof generation requests
console.log("🛡️ VERA Vault service worker loaded");

// Handle messages from content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log("[VERA BG] Received:", message.type);

  if (message.type === "STORE_CREDENTIAL") {
    storeCredential(message.credential)
      .then(() => {
        sendResponse({ success: true, type: "CREDENTIAL_STORED" });
      })
      .catch((err) => {
        console.error("[VERA BG] Store error:", err);
        sendResponse({ success: false, type: "STORE_ERROR", error: err.message });
      });
    return true; // Keep channel open for async response
  }


  if (message.type === "GENERATE_PROOF") {
    generateProof(message)
      .then((result) => {
        sendResponse({ type: "PROOF_GENERATED", ...result });
      })
      .catch((err) => {
        console.error("[VERA BG] Proof error:", err);
        sendResponse({ type: "PROOF_ERROR", error: err.message });
      });
    return true;
  }

  if (message.type === "PING") {
    sendResponse({ status: "VERA_WALLET_ACTIVE", type: "PONG" });
    return true;
  }
});

// Store a credential in chrome.storage.local
async function storeCredential(credentialData) {
  const result = await chrome.storage.local.get(["credentials"]);
  const credentials = result.credentials || [];
  credentials.push({
    ...credentialData,
    storedAt: new Date().toISOString(),
    id: `cred-${Date.now()}`,
  });
  await chrome.storage.local.set({ credentials });
  console.log(`[VERA BG] ✅ Credential stored. Total: ${credentials.length}`);
  
  // Update badge
  chrome.action.setBadgeText({ text: String(credentials.length) });
  chrome.action.setBadgeBackgroundColor({ color: "#4361ee" });
}

// Get all stored credentials
async function getCredentials() {
  const result = await chrome.storage.local.get(["credentials"]);
  return result.credentials || [];
}

// Find a credential matching storeID and itemSKU
async function findCredential(storeID, itemSKU) {
  const credentials = await getCredentials();
  return credentials.find(
    (c) =>
      c.credential &&
      c.credential.credentialSubject &&
      c.credential.credentialSubject.storeID === storeID &&
      c.credential.credentialSubject.itemSKU === itemSKU
  );
}

// Generate a selective disclosure proof
// Uses API FALLBACK (server-side proof derivation)
async function generateProof(request) {
  const { storeID, itemSKU, nonce } = request;

  // Find matching credential
  const credData = await findCredential(storeID, itemSKU);
  if (!credData) {
    throw new Error(`No credential found for Store: ${storeID}, Item: ${itemSKU}`);
  }

  console.log(`[VERA BG] Found credential, generating proof via API fallback...`);
  console.log(`[VERA BG] Revealing: StoreID (0), ItemSKU (1)`);
  console.log(`[VERA BG] Hiding: InvoiceID (2), PurchaseTimestamp (3)`);

  // Call backend API for proof generation (fallback)
  const response = await fetch("https://vera-api-buru.onrender.com/api/proofs/derive", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      rawMessages: credData.rawMessages,
      signature: credData.signature,
      publicKey: credData.publicKey,
      revealedIndices: [0, 1], // Reveal StoreID + ItemSKU only
      nonce: nonce,
    }),
  });

  if (!response.ok) {
    const err = await response.json();
    throw new Error(err.error || "Proof derivation failed");
  }

  const result = await response.json();
  console.log(`[VERA BG] ✅ Proof generated successfully`);
  return result;
}
