// import { withSentryConfig } from '@sentry/nextjs';
import { fileURLToPath } from 'url';
import { dirname, resolve } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Updated at: 2025-11-22 - Trigger restart for Prisma Schema
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'standalone',
  reactStrictMode: true,
  compress: true,
  swcMinify: true,
  eslint: {
    ignoreDuringBuilds: true,
  },
  typescript: {
    ignoreBuildErrors: true,
  },
  experimental: {
    // Exclude nodemailer from webpack bundling (use native Node.js require)
    serverComponentsExternalPackages: ['nodemailer', '@google/genai'],
  },

  webpack: (config, { webpack, nextRuntime }) => {
    // Reduce peak memory: serialize module compilation (default parallelism is 100)
    // 7.6GB Docker VM can't handle full parallel webpack compilation for a project this large
    config.parallelism = 5;

    // For Edge runtime (middleware), replace @upstash/redis with its Edge-compatible cloudflare
    // build. The default package entry (nodejs.mjs) uses Buffer and other Node.js globals
    // unavailable in the V8-based Edge runtime, causing silent middleware compilation failures.
    if (nextRuntime === 'edge') {
      config.plugins.push(
        new webpack.NormalModuleReplacementPlugin(
          /^@upstash\/redis$/,
          resolve(__dirname, 'node_modules/@upstash/redis/cloudflare.mjs')
        )
      );
    }

    // NormalModuleReplacementPlugin intercepts imports BEFORE tsconfig alias resolution,
    // ensuring @/convex/_generated/* always resolves to a file that exists.
    // 50+ API routes dynamically import these inside runtime conditionals — webpack
    // still tries to bundle them at compile time and fails without this fix.
    // Stubs live in lib/convex-stub/ which is mounted in Docker (convex/ is not).
    config.plugins.push(
      new webpack.NormalModuleReplacementPlugin(
        /^@\/convex\/_generated\/api$/,
        resolve(__dirname, 'lib/convex-stub/api.js')
      ),
      new webpack.NormalModuleReplacementPlugin(
        /^@\/convex\/_generated\/server$/,
        resolve(__dirname, 'lib/convex-stub/server.js')
      )
    );
    return config;
  },

  // Security headers
  async headers() {
    // HSTS header - only in real production (not localhost Docker)
    // Check for production domain to avoid breaking localhost testing
    const isRealProduction = process.env.NODE_ENV === 'production' &&
      process.env.NEXT_PUBLIC_APP_URL &&
      !process.env.NEXT_PUBLIC_APP_URL.includes('localhost');

    const hstsHeader = isRealProduction ? [
      {
        // 🔒 HSTS (HTTP Strict Transport Security)
        // Forces browsers to only connect via HTTPS for 2 years (including subdomains)
        // Prevents SSL stripping attacks and session hijacking
        key: 'Strict-Transport-Security',
        value: 'max-age=63072000; includeSubDomains; preload',
      },
    ] : [];

    return [
      {
        // ⚡ CACHE HEADERS - Blog performance optimization
        source: '/:lang/blog/:path*',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400',
          },
          {
            key: 'CDN-Cache-Control',
            value: 'max-age=3600',
          },
        ],
      },
      {
        // Apply security headers to all routes
        source: '/:path*',
        headers: [
          ...hstsHeader,
          {
            // 🔒 Clickjacking Protection
            // Prevents the site from being embedded in iframes on other domains
            // Stops attackers from overlaying invisible frames to steal clicks
            key: 'X-Frame-Options',
            value: 'DENY',
          },
          {
            // 🔒 MIME Type Sniffing Protection
            // Prevents browsers from interpreting files as different MIME types
            // Stops XSS attacks via malicious file uploads
            key: 'X-Content-Type-Options',
            value: 'nosniff',
          },
          {
            // 🔒 XSS Protection (Legacy browsers)
            // Enables browser's built-in XSS filter (backup for CSP)
            key: 'X-XSS-Protection',
            value: '1; mode=block',
          },
          {
            // 🔒 Referrer Policy
            // Controls how much referrer information is sent with requests
            // Protects user privacy and prevents leaking sensitive URLs
            key: 'Referrer-Policy',
            value: 'strict-origin-when-cross-origin',
          },
          {
            // 🔒 Permissions Policy (Feature Policy)
            // Disables unnecessary browser features that could be exploited
            // Allows microphone for ElevenLabs voice agent, blocks camera and geolocation
            key: 'Permissions-Policy',
            value: 'camera=(), microphone=(self), geolocation=(), interest-cohort=()',
          },
          // CSP is emitted from middleware.ts so Clerk, nonce, and route-specific
          // behavior come from a single source of truth. A second static CSP header
          // here causes the browser to intersect both policies and can block Clerk JS.
        ],
      },
    ];
  },
};

// Sentry temporarily disabled for development
// Uncomment to re-enable:
// const sentryEnabled = process.env.NEXT_PUBLIC_SENTRY_DSN;
// export default sentryEnabled ? withSentryConfig(nextConfig, {...}) : nextConfig;

export default nextConfig;
