/**
 * Measure max _id string length across all Mongo collections (read-only).
 */
import mongoose from "mongoose";
import fs from "fs";
import path from "path";

const uri = process.env.MONGODB_URI || "mongodb://localhost:27017/safar_libya";
const OUT = path.join(process.cwd(), "scripts", "id-length-report.json");

async function main() {
  await mongoose.connect(uri);
  const db = mongoose.connection.db!;
  const cols = (await db.listCollections().toArray()).map((c) => c.name).sort();
  let globalMax = 0;
  let globalSample = "";
  let globalCol = "";
  const per: Array<{ name: string; count: number; maxIdLen: number; sample: string }> = [];

  for (const name of cols) {
    const docs = await db.collection(name).find({}, { projection: { _id: 1 } }).toArray();
    let max = 0;
    let sample = "";
    for (const d of docs) {
      const s = String(d._id);
      if (s.length > max) {
        max = s.length;
        sample = s;
      }
    }
    per.push({ name, count: docs.length, maxIdLen: max, sample });
    if (max > globalMax) {
      globalMax = max;
      globalSample = sample;
      globalCol = name;
    }
  }

  const report = {
    analyzedAt: new Date().toISOString(),
    globalMaxIdLen: globalMax,
    globalCollection: globalCol,
    globalSample,
    varchar36Sufficient: globalMax <= 36,
    recommendedVarchar: Math.max(36, globalMax + 4),
    perCollection: per,
  };
  fs.writeFileSync(OUT, JSON.stringify(report, null, 2), "utf8");
  console.log(JSON.stringify(report, null, 2));
  await mongoose.disconnect();
}

main().catch(async (e) => {
  console.error(e);
  try {
    await mongoose.disconnect();
  } catch {
    /* ignore */
  }
  process.exit(1);
});
