import path from "node:path";
import type { NextConfig } from "next";
import { PHASE_PRODUCTION_BUILD } from "next/constants";

const isDev = process.env.NODE_ENV === "development"; // development | production

// "web" (app.rangook.ir) or "native" (the apps, set by scripts/native-build.js).
const APP_TARGET = process.env.NEXT_PUBLIC_APP_TARGET || "web";
if (APP_TARGET !== "web" && APP_TARGET !== "native") {
  throw new Error(`NEXT_PUBLIC_APP_TARGET must be "web" or "native", got "${APP_TARGET}".`);
}

// video.js's self-contained UMD build: kept away from Next's parser and JS loaders (see webpack below).
const VIDEOJS_UMD = /video\.js[\\/]dist[\\/]video\.min\.js$/;

type WebpackRule = {
  loader?: string;
  use?: unknown;
  exclude?: unknown;
  oneOf?: WebpackRule[];
  rules?: WebpackRule[];
};

/** Adds an exclude for the video.js UMD file to every SWC/Babel loader rule, however nested. */
function excludeFromJsLoaders(rules: unknown[]): void {
  for (const rule of rules) {
    if (!rule || typeof rule !== "object") continue;
    const r = rule as WebpackRule;

    if (/swc|babel/.test(JSON.stringify({ loader: r.loader, use: r.use }) ?? "")) {
      r.exclude = r.exclude ? [...(Array.isArray(r.exclude) ? r.exclude : [r.exclude]), VIDEOJS_UMD] : VIDEOJS_UMD;
    }

    if (Array.isArray(r.oneOf)) excludeFromJsLoaders(r.oneOf);
    if (Array.isArray(r.rules)) excludeFromJsLoaders(r.rules);
  }
}

export default function nextConfig(phase: string): NextConfig {
  return {
    reactStrictMode: !isDev,
    output: "export",
    trailingSlash: true,

    // Native builds export to Capacitor's webDir, never to ./out (the live website).
    ...(APP_TARGET === "native" && phase === PHASE_PRODUCTION_BUILD
      ? { distDir: "build/native/www" }
      : {}),

    // Always defined, so webpack sees a literal and drops the other target's code.
    env: {
      NEXT_PUBLIC_APP_TARGET: APP_TARGET,
    },

    // Next's own, first-class version of the cache-busting stamp we used to
    // hand-roll as the ?_r= query param. Next appends ?dpl=<id> to the static
    // asset URLs it emits and exposes the id to the client, so a deploy can
    // never serve a document whose chunk URLs collide with the previous
    // deploy's in any cache. Unlike ?_r= it lives only on asset requests --
    // page URLs stay clean, and next/link and useRouter can be used directly
    // with no wrappers.
    //
    // Fed from the same build id as version.json (scripts/generate-version.js
    // writes NEXT_PUBLIC_BUILD_ID into .env.local before `next build` runs), so
    // the asset stamp and the update check always agree on what "this build" is.
    //
    // Web only: with it, a static server makes every navigation a full page load.
    deploymentId: APP_TARGET === "web" ? process.env.NEXT_PUBLIC_BUILD_ID : undefined,

    images: {
      unoptimized: true
    },
    transpilePackages: [
      "lucide-react",
      "react-multi-date-picker",
      "react-phone-input-2"
    ],

    // video.js's HLS engine (VHS) runs decryption and transmuxing in Web Workers built
    // from its own code. Next replaces `typeof window` with "object" in client code
    // (its SWC optimiser and DefinePlugin), which turns the workers' window check into
    // `win = window` and crashes them ("window is not defined"): encrypted lessons never
    // play. So the self-contained UMD build is used, excluded from Next's JS loaders and
    // not parsed, and its worker code stays as shipped. Plugins that `import "video.js"`
    // get the same instance through the alias.
    webpack(config) {
      const videojsUmd = path.join(process.cwd(), "node_modules", "video.js", "dist", "video.min.js");

      config.resolve = config.resolve ?? {};
      config.resolve.alias = { ...(config.resolve.alias ?? {}), "video.js$": videojsUmd };

      config.module = config.module ?? {};
      const noParse = config.module.noParse;
      config.module.noParse = [...(noParse ? (Array.isArray(noParse) ? noParse : [noParse]) : []), VIDEOJS_UMD];
      excludeFromJsLoaders(config.module.rules ?? []);

      return config;
    },
  };
}
