export function viewLinkedAccountsPage() {
  if (localStorage.getItem("role") !== "administrator") return;

  window.addEventListener("DOMContentLoaded", (_e) => {
    Array.from(document.querySelectorAll(".user-card")).forEach(card => {
      let btn = document.createElement("button");
      btn.textContent = "✗";
      btn.classList = "remove-link";
      btn.addEventListener("click", async (e) => {
        // apparently it only actually stops if you use both:
        e.preventDefault();
        e.stopPropagation();

        let id = card.dataset["id"];
        let service = card.dataset["service"];

        if (confirm(`Delete the connection for user #${id} on ${service}?`)) {
          if (await deleteLinkedAccount(service, id)) {
            card.remove();
          } else {
            alert("Error");
          }
        }
      });
      card.appendChild(btn);
    });
  });
}

async function deleteLinkedAccount(service, id) {
  return (await fetch(`/${service}/user/${id}/links`, { method: "DELETE" })).status == 204;
}
