const { Client } = require("@microsoft/microsoft-graph-client");
require("isomorphic-fetch");
const { ConfidentialClientApplication } = require("@azure/identity");

// Azure AD credentials (replace with your actual credentials)
const clientId = "36b57ba8-6079-4942-9105-eafdb0be5754";
const clientSecret = "L3F8Q~PzXkPSlJjmsW6VKYJPZbWkc0sehUEwJcX3";
const tenantId = "b5d394fc-7d17-4e7d-8b52-c3b4e2de88be";

// Create an authentication client
const authClient = new ConfidentialClientApplication({
  auth: {
    clientId: clientId,
    clientSecret: clientSecret,
    authority: `https://login.microsoftonline.com/${tenantId}`,
  },
});

// Function to get access token for Microsoft Graph API
async function getAccessToken() {
  try {
    const result = await authClient.acquireTokenByClientCredential({
      scopes: ["https://graph.microsoft.com/.default"],
    });
    return result.accessToken;
  } catch (error) {
    console.error("Error acquiring access token:", error);
  }
}

// Function to create a Graph client instance
async function getGraphClient() {
  const accessToken = await getAccessToken();
  return Client.init({
    authProvider: (done) => {
      done(null, accessToken); // Pass the access token
    },
  });
}

// Function to fetch emails from the Office 365 inbox
async function fetchEmails() {
  try {
    const client = await getGraphClient();

    const messages = await client
      .api("/me/messages")
      .top(10) // Fetch the top 10 latest emails
      .select("subject,receivedDateTime,from") // Only fetch specific fields
      .orderby("receivedDateTime DESC") // Order by received date
      .get();

    console.log("Fetched Emails:");
    messages.value.forEach((message, index) => {
      console.log(`Email ${index + 1}:`);
      console.log(`  Subject: ${message.subject}`);
      console.log(`  From: ${message.from.emailAddress.address}`);
      console.log(`  Received: ${message.receivedDateTime}`);
      console.log("\n");
    });
  } catch (error) {
    console.error("Error fetching emails:", error);
  }
}

// Call the fetchEmails function
fetchEmails();
