// ═══════════════════════════════════════════════════════════════
// backend/services/googleSync.js
// NordSafe EHS — Google Sheets Sync Service
// ───────────────────────────────────────────────────────────────
// يُستخدم من داخل كل controller لمزامنة البيانات مع Google Sheets
// نفس فكرة sharepoint.js — لكن لـ Google
// ═══════════════════════════════════════════════════════════════
const { Companies } = require("../models");
const { appendRow, createCompanySpreadsheet } = require("./googleSheets");

// ─── mapping: نوع الـ record → اسم الـ Sheet ─────────────────
const SHEET_MAP = {
  "deviations":          "Deviations",
  "case-investigations": "Incidents",
  "site-monitoring":     "SiteMonitoring",
  "job-safety-analysis": "JSA",
  "toolbox-meeting":     "ToolboxMeetings",
  "pre-task-checklist":  "Checklists",
  "equipment-controller":"Equipment",
  "risk-assessment":     "RiskAssessments",
  "permit-to-work":      "Permits",
  "sds":                 "SDS",
};

// ─── Header map: نفس ترتيب columns في كل sheet ───────────────
const HEADER_MAP = {
  Incidents:       ["ID", "Title", "Status", "Severity", "Location", "Description", "ReportedBy", "IncidentDate",   "NordSafeId", "CreatedAt"],
  Deviations:      ["ID", "Title", "Status", "Category", "Location", "Description", "ReportedBy", "DeviationDate",  "NordSafeId", "CreatedAt"],
  RiskAssessments: ["ID", "Title", "Status", "RiskLevel", "Location", "Description", "AssessedBy", "ReviewDate",    "NordSafeId", "CreatedAt"],
  Permits:         ["ID", "Title", "Status", "PermitType","Location", "Description", "RequestedBy","ValidUntil",    "NordSafeId", "CreatedAt"],
  SiteMonitoring:  ["ID", "Title", "Status", "InspectionType","Location","Findings","InspectedBy","InspectionDate","NordSafeId", "CreatedAt"],
  JSA:             ["ID", "Title", "Status", "TaskActivity","Location","Description","PreparedBy", "",              "NordSafeId", "CreatedAt"],
  ToolboxMeetings: ["ID", "Title", "Topic", "Location","Participants","KeyPoints",  "ConductedBy","MeetingDate",   "NordSafeId", "CreatedAt"],
};

// ─── إعداد Google Sheets عند أول login ───────────────────────
const setupCompanyGoogle = async (companyId, accessToken, companyName) => {
  try {
    const result = await createCompanySpreadsheet(accessToken, companyName);

    await Companies.update(
      {
        googleConnected:     true,
        googleSpreadsheetId: result.spreadsheetId,
      },
      { where: { id: companyId } }
    );

    console.log(`✅ Google Sheets setup done: ${result.url}`);
    return { success: true, ...result };
  } catch (err) {
    console.error("Google setup failed:", err.message);
    return { success: false, error: err.message };
  }
};

// ─── مزامنة record مع Google Sheets ─────────────────────────
// يُستدعى بعد الحفظ في MySQL — بدون await
const syncToGoogle = async ({ companyId, recordType, recordId, fields }) => {
  try {
    const company = await Companies.findByPk(companyId);
    if (!company?.googleConnected || !company?.googleSpreadsheetId) return;

    const sheetName = SHEET_MAP[recordType];
    if (!sheetName) return;

    const headers = HEADER_MAP[sheetName];
    if (!headers) return;

    // بناء الـ row بنفس ترتيب الـ headers
    const now = new Date().toISOString().split("T")[0];
    const row = headers.map((h) => {
      if (h === "NordSafeId") return recordId.toString();
      if (h === "CreatedAt")  return now;
      if (h === "ID")         return recordId.toString();
      return fields[h] || "";
    });

    await appendRow(company.googleAccessToken, company.googleSpreadsheetId, sheetName, row);
    console.log(`✅ Synced to Google Sheets: ${sheetName} — ID ${recordId}`);
  } catch (err) {
    // لا توقف العملية الرئيسية
    console.error(`Google Sheets sync failed for ${recordType}:`, err.message);
  }
};

module.exports = { setupCompanyGoogle, syncToGoogle, SHEET_MAP };
