import axios from "axios";
import qs from "qs";
import fs from "fs";
import dotenv from "dotenv";

// -----------------------------
// CONFIG
// -----------------------------
dotenv.config();
// Load non‑sensitive values from config.json
const CONFIG = JSON.parse(fs.readFileSync("config.json", "utf8"));
const tenantId = CONFIG.tenantId;
const clientId = CONFIG.clientId;
const testSharePointFileUrl = CONFIG.testSharePointFileUrl;

// Load secret only from .env
const clientSecret = process.env.CLIENT_SECRET;

// -----------------------------
// Validation
// -----------------------------
const missing = [];
if (!tenantId) missing.push("tenantId");
if (!clientId) missing.push("clientId");
if (!clientSecret) missing.push("clientSecret");
if (!testSharePointFileUrl) missing.push("testSharePointFileUrl");

if (missing.length > 0) {
  console.error("❌ Missing values:", missing.join(", "));
  process.exit(1);
} else {
  console.log("✅ All required values present");
}

// -----------------------------
// 1. Get Graph Token (Client Credentials)
// -----------------------------
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",
  });

  try {
    const res = await axios.post(tokenUrl, body, {
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
    });

    console.log("✅ Token acquired");
    // can use to test to see the full token as needed, just remove this comment// console.log("🔑 Access Token:", res.data.access_token);
    return res.data.access_token;
    
  } catch (err) {
    console.error("❌ Failed to acquire token");
    console.error(err.response?.data || err.message);
    process.exit(1);
  }
}

// -----------------------------
// 2. Convert SharePoint File URL → Drive Item ID
// -----------------------------
function normalizeSharePointUrl(fileUrl) {
  return fileUrl
    .replace("guestaccess.aspx", "")
    .replace(/\?.*$/, ""); // remove ?query
}

// -----------------------------
// 3. Test GET file metadata
// -----------------------------
async function testFileAccess(token) {
  const cleanUrl = normalizeSharePointUrl(testSharePointFileUrl);

  console.log("🔎 Normalized URL:", cleanUrl);

  const graphUrl =
    `https://graph.microsoft.com/v1.0/shares/u!${Buffer.from(cleanUrl).toString("base64")}/driveItem`;

  try {
    const res = await axios.get(graphUrl, {
      headers: { Authorization: `Bearer ${token}` },
    });

    console.log("✅ SharePoint file access test succeeded!");
    console.log("File name:", res.data.name);
    console.log("Drive Item ID:", res.data.id);
  } catch (err) {
    console.error("❌ SharePoint file access failed");
    console.error(err.response?.data || err.message);
  }
}

// -----------------------------
// MAIN
// -----------------------------
(async () => {
  console.log("🔵 Testing SharePoint Access…");
  const token = await getGraphToken();
  await testFileAccess(token);
})();
