// sharepointDownload.js
import axios from "axios";
import qs from "qs";
import dotenv from "dotenv";
import fs from "fs";

dotenv.config();

// -----------------------------
// CONFIG
// -----------------------------
const CONFIG = JSON.parse(fs.readFileSync("config.json", "utf8"));
const tenantId = CONFIG.tenantId;
const clientId = CONFIG.clientId;

// Secret stays in .env
const clientSecret = process.env.CLIENT_SECRET;

// -----------------------------
// GRAPH TOKEN
// -----------------------------
async function getGraphToken() {
  const tokenUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
  const body = qs.stringify({
    client_id: clientId,
    client_secret: clientSecret,
    scope: "https://graph.microsoft.com/.default",
    grant_type: "client_credentials",
  });
  const res = await axios.post(tokenUrl, body, {
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
  });
  console.log("✅ Graph token acquired");
  return res.data.access_token;
}

// -----------------------------
// DOWNLOAD BY ITEM ID
// -----------------------------
// Example link: https://czflex.sharepoint.com/sites/Team/Shared%20Documents/General/JOBS%201000-9999.xlsx?d=wc20d9b5023f84403b4d345ca88382eb4
// The ?d=... part is the itemId
async function downloadFileById(graphToken, sitePath, itemId) {
  const url = `https://graph.microsoft.com/v1.0/sites/${sitePath}/drive/items/${itemId}/content`;
  const res = await axios.get(url, {
    headers: { Authorization: `Bearer ${graphToken}` },
    responseType: "arraybuffer",
  });
  console.log("✅ File downloaded, bytes:", res.data.byteLength);
  return res.data;
}

// -----------------------------
// MAIN
// -----------------------------
(async () => {
  try {
    const graphToken = await getGraphToken();

    // sitePath matches your site
    const sitePath = "czflex.sharepoint.com:/sites/Team";

    // itemId from your link (?d=...)
    const itemId = "wc20d9b5023f84403b4d345ca88382eb4";

    const buffer = await downloadFileById(graphToken, sitePath, itemId);

    // At this point you can feed buffer into XLSX.read(buffer, { type: "buffer", cellDates: true })
    // Example:
    // const workbook = XLSX.read(buffer, { type: "buffer", cellDates: true });
    // const sheetNames = workbook.SheetNames;
    // console.log("Sheets:", sheetNames);

  } catch (err) {
    console.error("❌ Error:", err.response?.data || err.message || err);
  }
})();
"id": "czflex.sharepoint.com,aaaa83f5-b1bd-4133-b60c-507030425863,0a423385-151c-44d7-b692-d85ae4bdfc0b"