document.addEventListener("DOMContentLoaded", function () {
  const form = document.getElementById("importForm");
  const resultDiv = document.getElementById("result");
  const exportBtn = document.getElementById("exportBtn");

  exportBtn.addEventListener("click", async function () {
    try {
      const response = await fetch("/api/v1/export", {
        method: "GET",
      });
      if (!response.ok) {
        const data = await response.json();
        resultDiv.textContent = "Error: " + (data.error || "Unknown error");
        return;
      }
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "transactions.csv";
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
      resultDiv.textContent = "Export successful!";
    } catch (err) {
      resultDiv.textContent = "Error: " + err.message;
    }
  });

  form.addEventListener("submit", async function (e) {
    e.preventDefault();
    const formData = new FormData(form);

    try {
      const response = await fetch("/api/v1/import", {
        method: "POST",
        body: formData,
      });
      const data = await response.json();
      if (data.success) {
        resultDiv.textContent = "Import successful!";
      } else {
        resultDiv.textContent = "Error: " + (data.error || "Unknown error");
      }
    } catch (err) {
      resultDiv.textContent = "Error: " + err.message;
    }
  });
});
