/* global process, URL */
import createNextIntlPlugin from "next-intl/plugin";
import { withSentryConfig } from "@sentry/nextjs";
import fs from "node:fs";
import path from "node:path";

/** @type {import('next').NextConfig} */
export const baseNextConfig = {
  output: "standalone",
  turbopack: {},
  images: {
    dangerouslyAllowSVG: true,
    contentDispositionType: "attachment",
    contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
  },
  async rewrites() {
    const umamiUrl = (
      process.env.NEXT_PUBLIC_UMAMI_SCRIPT_URL ||
      "https://analytics.infra.mintel.me"
    ).replace("/script.js", "");
    const glitchtipUrl = process.env.SENTRY_DSN
      ? new URL(process.env.SENTRY_DSN).origin
      : "https://errors.infra.mintel.me";

    return [
      {
        source: "/stats/:path*",
        destination: `${umamiUrl}/:path*`,
      },
      {
        source: "/errors/:path*",
        destination: `${glitchtipUrl}/:path*`,
      },
    ];
  },
};

const withMintelConfig = (config) => {
  const i18nPaths = [
    "src/i18n/request.ts",
    "src/i18n/request.tsx",
    "i18n/request.ts",
    "i18n/request.tsx",
    "src/i18n.ts",
    "src/i18n.tsx",
    "i18n.ts",
    "i18n.tsx",
  ];

  const hasI18nConfig = i18nPaths.some((p) =>
    fs.existsSync(path.resolve(process.cwd(), p)),
  );

  let nextConfig = { ...baseNextConfig, ...config };

  if (hasI18nConfig) {
    const withNextIntl = createNextIntlPlugin();
    nextConfig = withNextIntl(nextConfig);
  }

  return withSentryConfig(
    nextConfig,
    {
      silent: !process.env.CI,
      treeshake: { removeDebugLogging: true },
    },
    {
      authToken: undefined,
    },
  );
};

export default withMintelConfig;
