"use strict";

const analysisStatus = document.getElementById("analysis-status");
const summaryConsentStates = document.getElementById("summary-consent-states");
const summaryObservedRequests = document.getElementById(
  "summary-observed-requests"
);
const summaryGvlSnapshots = document.getElementById("summary-gvl-snapshots");
const summaryCurrentGvlVersion = document.getElementById(
  "summary-current-gvl-version"
);

document.addEventListener("DOMContentLoaded", async () => {
  await renderAnalysisSummary();
});

async function renderAnalysisSummary() {
  try {
    const [evidenceStatus, gvlStatus] = await Promise.all([
      getEvidenceRetentionStatus(),
      getLatestGvlUpdateStatus()
    ]);

    const storeCounts = evidenceStatus.storeCounts ?? {};
    const status = gvlStatus.status ?? {};

    summaryConsentStates.textContent = String(storeCounts.consent_states ?? 0);
    summaryObservedRequests.textContent = String(
      storeCounts.observed_requests ?? 0
    );
    summaryGvlSnapshots.textContent = String(storeCounts.gvl_snapshots ?? 0);
    summaryCurrentGvlVersion.textContent = formatNullable(
      status.latestLocalVendorListVersion ?? status.currentVendorListVersion
    );
    analysisStatus.textContent = "Datenbestände geladen";
  } catch (error) {
    summaryConsentStates.textContent = "-";
    summaryObservedRequests.textContent = "-";
    summaryGvlSnapshots.textContent = "-";
    summaryCurrentGvlVersion.textContent = "-";
    analysisStatus.textContent = "Datenbestände konnten nicht geladen werden";
    console.warn("VG-Observe analysis dashboard summary failed", error);
  }
}

async function getEvidenceRetentionStatus() {
  const status = await browser.runtime.sendMessage({
    type: "get_evidence_retention_status"
  });

  if (!status?.success) {
    throw new Error(status?.error ?? "get_evidence_retention_status_failed");
  }

  return status;
}

async function getLatestGvlUpdateStatus() {
  const status = await browser.runtime.sendMessage({
    type: "get_latest_gvl_update_status"
  });

  if (!status?.success) {
    throw new Error(status?.error ?? "get_latest_gvl_update_status_failed");
  }

  return status;
}

function formatNullable(value) {
  if (value === null || value === undefined || value === "") {
    return "-";
  }

  return String(value);
}
