import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiGet, apiPost } from "../lib/api";

export function useHasPassword() {
	return useQuery({
		queryKey: ["account", "hasPassword"],
		queryFn: () =>
			apiGet<{ hasPassword: boolean }>("/api/account/has-password"),
	});
}

export function useChangePassword() {
	return useMutation({
		mutationFn: (data: { currentPassword: string; newPassword: string }) =>
			apiPost<{ ok: boolean }>("/api/account/password", data),
	});
}

export function useChangeEmail() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (data: { newEmail: string }) =>
			apiPost<{ ok: boolean; email: string }>("/api/account/email", data),
		onSuccess: (_data, variables) => {
			// Update auth cache with new email since the OIDC session still has the old one
			queryClient.setQueryData(["auth"], (old: any) => {
				if (!old?.user) return old;
				return { ...old, user: { ...old.user, email: variables.newEmail } };
			});
		},
	});
}

export function useDeleteAccount() {
	return useMutation({
		mutationFn: () =>
			apiPost<{ ok: boolean; redirectTo: string }>("/api/account/delete", {
				confirmation: "DELETE",
			}),
	});
}
