import * as signalR from "@microsoft/signalr";

import { refreshToken } from "@/contracts/identity";

function getAccessToken() {
	try {
		const token = localStorage.getItem("token");
		return token || "";
	} catch {
		return "";
	}
}

export function createHubConnection() {
	const connection = new signalR.HubConnectionBuilder()
		.withUrl("/hubs/notifications", {
			accessTokenFactory: () => getAccessToken(),
			skipNegotiation: false,
		})
		.withAutomaticReconnect({
			nextRetryDelayInMilliseconds: () => 1000,
		})
		.configureLogging(signalR.LogLevel.Information)
		.build();

	connection.onclose(async (error) => {
		if (error instanceof signalR.HttpError && error.statusCode === 401) {
			try {
				await refreshToken();
				await connection?.start();
			} catch (refreshError) {
				console.error(
					"Reconnection after refresh failed",
					refreshError,
				);
			}
		}
	});

	return connection;
}
