import { ConnectedAircraft, ConnectedDispatcher } from "@repo/db";
import axios from "axios";
import { getSession } from "next-auth/react";

export const serverApi = axios.create({
	baseURL: process.env.NEXT_PUBLIC_DISPATCH_SERVER_URL,
	timeout: 10000,
	headers: {
		"Content-Type": "application/json",
	},
});

serverApi.interceptors.request.use(
	async (config) => {
		const session = await getSession();
		const token = session?.user.id; /* session?.accessToken */ // abhängig von deinem NextAuth setup

		if (token) {
			config.headers.Authorization = `User ${token}`;
		}

		return config;
	},
	(error) => {
		return Promise.reject(error);
	},
);

export const getConenctedUsers = async (): Promise<
	(ConnectedDispatcher | ConnectedAircraft)[]
> => {
	const res = await serverApi.get<(ConnectedDispatcher | ConnectedAircraft)[]>(
		"/status/connected-users",
	);
	if (res.status !== 200) {
		throw new Error("Failed to fetch connected users");
	}
	return res.data;
};
