import { afterAll } from "bun:test";

const originalWarn = console.warn;
const warnings: string[] = [];
const allowed = (process.env.WRNEXUS_TEST_WARNING_ALLOWLIST ?? "")
  .split(",")
  .map((value) => value.trim())
  .filter(Boolean);

console.warn = (...values: unknown[]) => {
  const message = values
    .map((value) => (typeof value === "string" ? value : JSON.stringify(value)))
    .join(" ");
  if (!allowed.some((pattern) => message.includes(pattern))) warnings.push(message);
  originalWarn(...values);
};

afterAll(() => {
  console.warn = originalWarn;
  if (warnings.length) {
    throw new Error(
      `WRN-TEST-UNEXPECTED-WARNING: ${warnings.length} warning(s) emitted:\n${warnings
        .map((warning) => `- ${warning}`)
        .join("\n")}`,
    );
  }
});
