import { Alpine } from "./alpine";
import { removeToken } from "./storage";
import { showToast } from "./toast";

async function confirmDeleteAccount(): Promise<void> {
  if (
    !confirm(
      "Are you sure? All preferences and devices will be deleted. This action cannot be undone.",
    )
  ) {
    return;
  }

  const token = localStorage.getItem("token");
  if (!token) {
    window.location.href = "/login";
    return;
  }

  try {
    const response = await fetch("/api/auth/profile", {
      method: "DELETE",
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    if (response.ok) {
      removeToken();
      localStorage.removeItem("user");
      window.location.href = "/login?deleted=true";
    } else {
      const error = await response.json();
      showToast(error.error || "Failed to delete account", "error");
    }
  } catch (error) {
    console.error("Failed to delete account", error);
    showToast("Failed to delete account", "error");
  }
}

export { confirmDeleteAccount };

Alpine.data("profile", () => ({
  confirmDeleteAccount,
}));
