import { MicrosoftGraphUser } from "../types/MSAuthTypes";

/**
 * Fetch Microsoft User
 *
 * This function fetches user data from Microsoft Graph API using the provided access token.
 * It makes a GET request to the `/me` endpoint and returns the user data in JSON format.
 *
 * @param accessToken - This is the access token provided by Microsoft.
 * @returns - Raw API Data from Microsoft.
 */
export const fetchMicrosoftUser = async (
  accessToken: string,
): Promise<MicrosoftGraphUser> => {
  const graphEndpoint = "https://graph.microsoft.com/v1.0/me";

  const response = await fetch(graphEndpoint, {
    method: "GET",
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });

  if (!response.ok) {
    throw new Error(
      `Graph request failed: ${response.status} ${response.statusText}`,
    );
  }

  const data = (await response.json()) as MicrosoftGraphUser;

  return data;
};
