import { cache } from "react";
import { API_URL } from "./constants";
import { ApiResponse } from "@/types/types";
import IUser from "@/interfaces/IUser";
import { cookies } from "next/headers";
import { getApiUrl } from "@/utils/api";

const getMe = cache(
	async (sessionCookie?: string): Promise<ApiResponse<IUser> | null> => {
		if (!sessionCookie) {
			const store = await cookies();
			const token = store.get("auth_token")?.value;
			if (!token) return null;
			sessionCookie = token;
		}
		const res = await fetch(`${getApiUrl()}/users/me`, {
			headers: { Authorization: `Bearer ${sessionCookie}` },
		});
		return await res.json();
	},
);

export default getMe;
