const path = require('path');
const webpack = require('webpack');

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false,
  serverExternalPackages: ['onnxruntime-node'],
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          { key: 'Cross-Origin-Opener-Policy', value: 'same-origin' },
          { key: 'Cross-Origin-Embedder-Policy', value: 'require-corp' },
        ],
      },
      {
        // Workers loaded via `new Worker(new URL(...))` need CORP cross-origin
        // so the parent page (with COEP) is allowed to embed them. Same-origin
        // workers don't need this but adding it doesn't hurt.
        source: '/_next/static/:path*',
        headers: [
          { key: 'Cross-Origin-Resource-Policy', value: 'same-origin' },
        ],
      },
      {
        source: '/ffmpeg/:path*',
        headers: [
          { key: 'Cross-Origin-Resource-Policy', value: 'same-origin' },
        ],
      },
    ];
  },
  webpack: (config, { isServer }) => {
    config.resolve.fallback = { ...config.resolve.fallback, fs: false, path: false };

    if (!isServer) {
      // Replace onnxruntime-node with our local stub BEFORE webpack even
      // looks at its package.json — this prevents the dynamic require of
      // a `.node` binary inside `binding.js`.
      config.resolve.alias = {
        ...config.resolve.alias,
        'onnxruntime-node$': path.resolve(
          __dirname,
          'src/lib/captions/onnxruntime-node-stub.js',
        ),
        '@xenova/transformers/node_modules/onnxruntime-node$': path.resolve(
          __dirname,
          'src/lib/captions/onnxruntime-node-stub.js',
        ),
      };
      config.resolve.alias = {
        ...config.resolve.alias,
        sharp: false,
      };
      config.module.rules.push({
        test: /\.node$/,
        use: 'ignore-loader',
      });
    }
    return config;
  },
};

module.exports = nextConfig;