//works to update pb field
import dotenv from "dotenv";
import PocketBase from "pocketbase";
import fs from "fs";

dotenv.config();

// -----------------------------
// CONFIG
// -----------------------------
const CONFIG = JSON.parse(fs.readFileSync("config.json", "utf8"));
const pbUrl = CONFIG.pbUrl;
const pbCollection = CONFIG.pbCollection;
const pbEmail = CONFIG.pbEmail;
const pbPassword = process.env.PB_PASSWORD;

// -----------------------------
// PB LOGIN
// -----------------------------
async function getPocketBaseClient() {
  const pb = new PocketBase(pbUrl);
  await pb.collection("users").authWithPassword(pbEmail, pbPassword);
  console.log("✅ PocketBase token acquired");
  return pb;
}

// -----------------------------
// UPDATE FROM JSON EXPORT
// -----------------------------
async function updateFromJSON(pb) {
  const data = JSON.parse(fs.readFileSync("records.json", "utf8"));
  const errors = [];

  for (const record of data) {
    try {
      // Strip system fields from payload
      const { id, created, updated, expand, ...payload } = record;

      // Update by id
      await pb.collection(pbCollection).update(id, payload);
    } catch (err) {
      errors.push({ id: record.id, error: err.message });
    }
  }

  if (errors.length) {
    console.error("❌ Errors during update:", errors);
  } else {
    console.log("✅ All records updated successfully");
  }

  return data;
}

// -----------------------------
// FETCH CURRENT RECORDS
// -----------------------------
async function getPocketBaseRecords(pb) {
  return await pb.collection(pbCollection).getFullList();
}

// -----------------------------
// NORMALIZATION HELPERS
// -----------------------------
function normalizeValue(field, value) {
  // Adjust based on common PB schema rules
  if (value === undefined) return null;

  // Example: treat text fields like Note_Ref as "" when empty
  if (field.toLowerCase().includes("note") || field.toLowerCase().includes("ref")) {
    return value === null ? "" : String(value);
  }

  // Numbers
  if (typeof value === "number") return value;
  if (value === null || value === "") return null;

  // Booleans
  if (typeof value === "boolean") return value;

  // Dates
  if (value instanceof Date) return value.toISOString();
  if (Date.parse(value)) return new Date(value).toISOString();

  return value;
}

// -----------------------------
// COMPARE ORIGINAL VS CURRENT
// -----------------------------
function compareRecords(original, current) {
  const diffs = [];
  for (const orig of original) {
    const curr = current.find(r => r.id === orig.id);
    if (!curr) {
      diffs.push({ id: orig.id, issue: "Missing in current DB" });
      continue;
    }

    const fields = Object.keys(orig).filter(
      k => !["id", "created", "updated", "expand"].includes(k)
    );

    for (const f of fields) {
      const origVal = normalizeValue(f, orig[f]);
      const currVal = normalizeValue(f, curr[f]);
      if (origVal !== currVal) {
        diffs.push({
          id: orig.id,
          field: f,
          original: origVal,
          current: currVal
        });
      }
    }
  }
  return diffs;
}

// -----------------------------
// MAIN TEST
// -----------------------------
(async () => {
  const pb = await getPocketBaseClient();

  // Step 1: Update from your existing export
  const original = await updateFromJSON(pb);

  // Step 2: Fetch current records
  const current = await getPocketBaseRecords(pb);

  // Step 3: Compare
  const diffs = compareRecords(original, current);

  if (diffs.length) {
    console.error("❌ Differences found:");
    for (const d of diffs) {
      console.log(
        `Record ${d.id}, field ${d.field}\n  original: ${d.original}\n  current : ${d.current}\n`
      );
    }
  } else {
    console.log("✅ No differences — round‑trip succeeded");
  }
})();