// excelsync.js
import fs from "fs";
import axios from "axios";
import qs from "qs";
// may need for reading excel
//import * as XLSX from "xlsx";
import dotenv from "dotenv";
// may need to serve html to port
//import { serve } from "bun";
import PocketBase from "pocketbase"

dotenv.config(); // connects to .env for sensitive info

// -----------------------------
// EXCEL PARSER
// -----------------------------
const HEADER_ROW_INDEX = 2;       // O index --> Row 3 Actual
const DATA_START_ROW_INDEX = 3;   // 0 index --> Row 4 Actual
const RANGE_HEADER_ROW = 3        // Excel index headers
const RANGE_DATA_ROW = 4          // Excel index data

// -----------------------------
// CONFIG
// -----------------------------
const CONFIG = JSON.parse(fs.readFileSync("config.json", "utf8"));
const tenantId = CONFIG.tenantId;
const clientId = CONFIG.clientId;
//const sharepointFileUrl = CONFIG.sharepointFileUrl; // production Excel file URL
const pbUrl = CONFIG.pbUrl;
const pbCollection = CONFIG.pbCollection || "Job_Info_TestEnv";
const pbEmail = CONFIG.pbEmail;
const clientSecret = process.env.CLIENT_SECRET;
const pbPassword = process.env.PB_PASSWORD;

// -----------------------------
// LOGGING
// -----------------------------
function log(message) {
  console.log(message);
  fs.appendFileSync("excelsync.log", message + "\n");
}

// -----------------------------
// 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" },
  });
  log("✅ Graph token acquired");
  return res.data.access_token;
}
// -----------------------------
// POCKETBASE LOGIN AND TOKEN
// -----------------------------
async function getPocketBaseClient() {
  const pb = new PocketBase(pbUrl);
  await pb.collection("users").authWithPassword(pbEmail, pbPassword);
  log("✅ PocketBase token acquired");
  return pb;
}

// -----------------------------
// HEADER MAP
// -----------------------------
const HEADER_MAP = {
  "Job_Number": "Job_Number",
  "Job_Full_Name": "Job_Full_Name",
  "Job_Name": "Job_Name",
  "Job Address": "Job_Address",
  "Job Type": "Job_Type",
  "Flag": "Flag",
  "Tax_Exempt": "Tax_Exempt",
  "Job Status": "Job_Status",
  "Job Division": "Job_Division",
  "Estimator": "Estimator",
  "Office Rep": "Office_Rep",
  "Manager": "Project_Manager",
  "Company/Client": "Company_Client",
  "Contact Person": "Contact_Person",
  "Phone Number": "Phone_Number",
  "Email": "Email",
  "Due Date": "Due_Date",
  "Due Date Source": "Due_Date_Source",
  "Due Date Counter": "Due_Date_Counter",
  "Due Time": "Due_Time",
  "Tax_Exempt_Docs_Uploaded": "Tax_Exempt_Docs_Uploaded",
  "Docs Uploaded": "Docs_Uploaded",
  "QB Created": "QB_Created",
  "Added to Calendar": "Added_To_Calendar",
  "PSwift Uploaded": "PSwift_Uploaded",
  "Voxer Created": "Voxer_Created",
  "Estimate Reviewed": "Estimate_Reviewed",
  "Estimate Draft": "Estimate_Draft",
  "Estimate Approved": "Estimate_Approved",
  "Start Date": "Start_Date",
  "Schedule_Confidence": "Schedule_Confidence",
  "Notes": "Notes",
  "Job QB Link": "Job_QB_Link",
  "Voxer Link": "Voxer_Link",
  "Job_Codes": "Job_Codes",
  "Submission Date": "Submission_Date",
  "Active": "Active",
  "Job Folder Link": "Job_Folder_Link",
  "pb_id": "id"
};

// -----------------------------
// MAIN
// -----------------------------
(async () => {
  try {
    log("🔵 Checking token acquisition and excel readiness");

    const graphToken = await getGraphToken();
    const pb = await getPocketBaseClient();
    // These can be update if the Excel File changes
    //const driveId = "b!9YOqqr2xM0G2DFBwMEJYY4UzQgocFddEtpLYWuS9_AtkCKl2q8yjQJteQ7Ti4QSx";
    //const itemId = "01SPNXLDSQTMG4F6BDANCLJU2FZKEDQLVU"

    await exceltopb(graphToken, driveId, itemId, "Job Sheet", pb);
    await pbtoupdate(pbCollection);

    log("✅ Ready for updating!");
  } catch (err) {
    log("❌ Error, not ready for updating." + (err.message || err));
    process.exit(1);
  }
})();