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 superEmail = process.env.Super_Email;
const superPassword = process.env.Super_Password;

// -----------------------------
// ADMIN LOGIN
// -----------------------------
async function getPocketBaseClient() {
  const pb = new PocketBase(pbUrl);
  await pb.admins.authWithPassword(superEmail, superPassword);
  console.log("✅ Admin token acquired");
  return pb;
}

// -----------------------------
// FETCH SCHEMA & SAVE TO FILE
// -----------------------------
async function getAndSaveSchema(pb) {
  const collection = await pb.collections.getOne(pbCollection);

  // Debug: log the full collection object so you can inspect it
  console.log("📦 Collection object:", JSON.stringify(collection, null, 2));

  if (!collection.schema) {
    console.error("❌ No schema property found on collection object.");
    return {};
  }

  // Build schema map (fieldName → type)
  const schemaMap = {};
  for (const field of collection.schema) {
    schemaMap[field.name] = field.type;
  }

  // Save full schema JSON for later use
  fs.writeFileSync("schema.json", JSON.stringify(collection.schema, null, 2), "utf8");

  console.log("✅ Schema saved to schema.json");
  console.log("Schema map:", schemaMap);

  return schemaMap;
}

// -----------------------------
// MAIN
// -----------------------------
(async () => {
  try {
    const pb = await getPocketBaseClient();
    await getAndSaveSchema(pb);
  } catch (err) {
    console.error("❌ Error fetching schema:", err);
  }
})();