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

interface AuthState {
	user: { id: string; email?: string; createdAt?: string } | null;
	authenticated: boolean;
}

export function useAuth() {
	return useQuery({
		queryKey: ["auth"],
		queryFn: () => apiGet<AuthState>("/api/auth/me"),
		staleTime: 5 * 60 * 1000,
		retry: false,
	});
}

export function useLogout() {
	const logout = () => {
		window.location.href = "/logout";
	};
	return { logout };
}

interface ApiKeyListItem {
	id: number;
	name: string;
	keyPrefix: string;
	createdAt: string;
}

interface ApiKeyResponse {
	id: number;
	name: string;
	key: string;
	prefix: string;
}

export function useApiKeys() {
	return useQuery({
		queryKey: ["apiKeys"],
		queryFn: () => apiGet<ApiKeyListItem[]>("/api/auth/keys"),
	});
}

export function useCreateApiKey() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (data: { name: string }) =>
			apiPost<ApiKeyResponse>("/api/auth/keys", data),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["apiKeys"] });
		},
	});
}

export function useDeleteApiKey() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (id: number) =>
			apiDelete<{ success: boolean }>(`/api/auth/keys/${id}`),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["apiKeys"] });
		},
	});
}
