import fs from "node:fs/promises";
import path from "node:path";

const OUT = path.join(process.cwd(), "public", "_auth", "whoami");

const groupsRaw = process.env.PUBLIC_WHOAMI_GROUPS ?? "editors";
const user = process.env.PUBLIC_WHOAMI_USER ?? "dev";
const name = process.env.PUBLIC_WHOAMI_NAME ?? "Dev Local";
const email = process.env.PUBLIC_WHOAMI_EMAIL ?? "area.technik@proton.me";

const groups = groupsRaw
  .split(/[;,]/)
  .map((s) => s.trim())
  .filter(Boolean)
  .join(",");

const body =
  `Remote-User: ${user}\n` +
  `Remote-Name: ${name}\n` +
  `Remote-Email: ${email}\n` +
  `Remote-Groups: ${groups}\n`;

await fs.mkdir(path.dirname(OUT), { recursive: true });
await fs.writeFile(OUT, body, "utf8");

console.log(`✅ dev whoami written: ${path.relative(process.cwd(), OUT)} (${groups})`);