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

interface PublicProfile {
	id: number;
	displayName: string | null;
	avatarUrl: string | null;
	avatarImageUrl: string | null;
	bio: string | null;
	setups: { id: number; name: string; createdAt: string }[];
}

interface UpdateProfileData {
	displayName?: string;
	avatarUrl?: string | null;
	bio?: string;
}

interface ProfileResponse {
	id: number;
	displayName: string | null;
	avatarUrl: string | null;
	bio: string | null;
}

export function usePublicProfile(userId: number | null) {
	return useQuery({
		queryKey: ["profiles", userId],
		queryFn: () => apiGet<PublicProfile>(`/api/users/${userId}/profile`),
		enabled: userId != null,
	});
}

export function useUpdateProfile() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (data: UpdateProfileData) =>
			apiPut<ProfileResponse>("/api/auth/profile", data),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["profiles"] });
			queryClient.invalidateQueries({ queryKey: ["auth"] });
		},
	});
}
