import type { NextConfig } from 'next';
import os from 'node:os';
import path from 'node:path';

function resolveAllowedDevOrigins(): string[] {
  const origins = new Set<string>(['localhost:3000', '127.0.0.1:3000']);
  const port = process.env.PORT || '3000';

  const extra = process.env.NEXT_ALLOWED_DEV_ORIGINS;
  if (extra) {
    for (const item of extra.split(',')) {
      const trimmed = item.trim();
      if (trimmed) origins.add(trimmed);
    }
  }

  if (process.env.NODE_ENV !== 'production') {
    const nets = os.networkInterfaces();
    for (const iface of Object.values(nets)) {
      for (const addr of iface ?? []) {
        if (addr.family === 'IPv4' && !addr.internal) {
          origins.add(`${addr.address}:${port}`);
          origins.add(addr.address);
        }
      }
    }
  }

  return Array.from(origins);
}

/** Origin of the API the browser calls, read from BACKEND_URL; empty when the API is served from the same address as the site. */
function resolveApiOrigin(): string {
  try {
    const raw = process.env.BACKEND_URL;
    if (!raw) return '';
    return new URL(raw).origin;
  } catch {
    return '';
  }
}

const isProduction = process.env.NODE_ENV === 'production';

const cspHeader = [
  "default-src 'self'",
  isProduction ? "script-src 'self' 'unsafe-inline'" : "script-src 'self' 'unsafe-inline' 'unsafe-eval'",
  "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
  "font-src 'self' https://fonts.gstatic.com data:",
  "img-src 'self' data: blob: https:",
  isProduction ? ["connect-src 'self'", resolveApiOrigin()].filter(Boolean).join(' ') : "connect-src 'self' http: https: ws: wss:",
  "frame-ancestors 'none'",
  "object-src 'none'",
  "base-uri 'self'",
  "form-action 'self'",
].join('; ');

const securityHeaders = [
  { key: 'Content-Security-Policy', value: cspHeader },
  { key: 'X-Content-Type-Options', value: 'nosniff' },
  { key: 'X-Frame-Options', value: 'DENY' },
  { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
  { key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=()' },
  ...(isProduction ? [{ key: 'Strict-Transport-Security', value: 'max-age=31536000; includeSubDomains' }] : []),
];

const nextConfig: NextConfig = {
  env: {
    BACKEND_URL: process.env.BACKEND_URL,
  },
  poweredByHeader: false,
  async rewrites() {
    const target = process.env.BACKEND_URL?.trim().replace(/\/+$/, '');
    if (!target) {
      throw new Error('BACKEND_URL environment variable is not defined');
    }
    return [
      {
        source: '/api/:path*',
        destination: `${target}/:path*`,
      },
    ];
  },
  async headers() {
    return [{ source: '/:path*', headers: securityHeaders }];
  },
  allowedDevOrigins: resolveAllowedDevOrigins(),
  experimental: {
    turbopackPluginRuntimeStrategy: 'forceWorkerThreads' as unknown as undefined,
  },
  turbopack: {
    root: path.resolve(__dirname),
    rules: {
      '*.css': {
        loaders: ['@tailwindcss/turbopack'],
        as: '*.css',
      },
    },
  },
};

export default nextConfig;
