/**
 * App-Only Authentication for SharePoint
 * 
 * Uses client credentials flow (application permissions)
 * instead of delegated permissions (user authentication)
 */

const fetch = require("node-fetch");

const MICROSOFT_CLIENT_ID = process.env.MICROSOFT_CLIENT_ID;
const MICROSOFT_CLIENT_SECRET = process.env.MICROSOFT_CLIENT_SECRET;
const MICROSOFT_TENANT_ID = process.env.MICROSOFT_TENANT_ID || "8fe3321f-727d-4c35-a7f7-452493485284";

/**
 * Get an app-only access token using client credentials flow
 * This token has application permissions, not user permissions
 */
async function getAppOnlyAccessToken() {
  if (!MICROSOFT_CLIENT_ID || !MICROSOFT_CLIENT_SECRET) {
    throw new Error("MICROSOFT_CLIENT_ID / MICROSOFT_CLIENT_SECRET not configured");
  }

  const tokenUrl = `https://login.microsoftonline.com/${MICROSOFT_TENANT_ID}/oauth2/v2.0/token`;
  
  const body = new URLSearchParams({
    client_id: MICROSOFT_CLIENT_ID,
    client_secret: MICROSOFT_CLIENT_SECRET,
    scope: "https://graph.microsoft.com/.default",
    grant_type: "client_credentials",
  });

  console.log("🔑 Requesting app-only access token...");
  
  const response = await fetch(tokenUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: body.toString(),
  });

  const data = await response.json();

  if (!response.ok) {
    console.error("❌ Failed to get app-only token:", data);
    throw new Error(data.error_description || data.error || "Failed to get app-only token");
  }

  console.log("✅ App-only access token obtained");
  return data.access_token;
}

module.exports = {
  getAppOnlyAccessToken,
};
