import type { NextConfig } from "next";
import os from "os";

// Comma-separated list of additional dev-server origins (LAN IPs etc.)
// allowed to hit HMR endpoints. Example: NEXT_DEV_ORIGINS="192.168.1.10,my.dev.local"
const devOrigins = (process.env.NEXT_DEV_ORIGINS ?? "")
  .split(",")
  .map((s) => s.trim())
  .filter(Boolean);

// This machine's own current LAN addresses, read at startup so they follow
// address changes. A page opened by an address that is not allowed has its
// hot-reload connection refused and keeps reloading itself.
const ownAddresses = Object.values(os.networkInterfaces())
  .flat()
  .filter((i): i is os.NetworkInterfaceInfo => !!i && i.family === "IPv4" && !i.internal)
  .map((i) => i.address);

const nextConfig: NextConfig = {
  // Next.js 16's allowedDevOrigins requires exact origins — no wildcards.
  // Extra origins can be added via the NEXT_DEV_ORIGINS env var, or listed
  // here explicitly.
  allowedDevOrigins: [
    "localhost",
    "127.0.0.1",
    ...ownAddresses,
    ...devOrigins,
  ],
};

export default nextConfig;
