import api from "@shared/api"
import { useAppSelector } from "@shared/hooks/useAppSelector"
import { resolveTaskProgressState } from "@shared/lib/taskProgress"

interface UseTaskProgressStateArgs {
	jobId: string | null
	enabled: boolean
	defaultMessage: string
}

export function useTaskProgressState({
	jobId,
	enabled,
	defaultMessage,
}: UseTaskProgressStateArgs): {
	progressPct: number
	message: string
	status: string | null
	errorMessage: string | null
} {
	const notification = useAppSelector((state) =>
		jobId
			? state.notifications.items.find((n) => n.job_id === jobId)
			: null,
	)

	const { data: taskStatus } = api.useQuery(
		"get",
		"/api/tasks/status/{job_id}/",
		{ params: { path: { job_id: jobId ?? "" } } },
		{
			enabled,
			refetchInterval: 2000,
		},
	)

	const resolvedState = resolveTaskProgressState({
		notificationMessage: notification?.message,
		notificationProgressPct: notification?.progress_pct,
		taskMessage: taskStatus?.current_message,
		taskProgressPct: taskStatus?.progress_pct,
		defaultMessage,
	})

	return {
		progressPct: resolvedState.progressPct,
		message: resolvedState.message,
		status: notification?.status ?? taskStatus?.status ?? null,
		errorMessage:
			notification?.message ?? taskStatus?.error_message ?? null,
	}
}
