import { withPayload } from '@payloadcms/next/withPayload'
import type { NextConfig } from 'next'
import path from 'path'
import { fileURLToPath } from 'url'

const dirname = path.dirname(fileURLToPath(import.meta.url))

// The static site (until September 2026) used .html addresses; keep every old link working.
const legacy: [string, string][] = [
  ['/index.html', '/'],
  ['/courses.html', '/courses'],
  ['/pricing.html', '/pricing'],
  ['/about.html', '/about'],
  ['/course/:slug.html', '/courses/:slug'],
  ['/en/index.html', '/en'],
  ['/en/courses.html', '/en/courses'],
  ['/en/pricing.html', '/en/pricing'],
  ['/en/about.html', '/en/about'],
  ['/en/course/:slug.html', '/en/courses/:slug'],
]

const nextConfig: NextConfig = {
  output: 'standalone',
  poweredByHeader: false,
  images: { localPatterns: [{ pathname: '/api/media/file/**' }] },
  async redirects() {
    return legacy.map(([source, destination]) => ({ source, destination, permanent: true }))
  },
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          { key: 'X-Content-Type-Options', value: 'nosniff' },
          { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
          { key: 'X-Frame-Options', value: 'SAMEORIGIN' },
        ],
      },
    ]
  },
  webpack: (webpackConfig) => {
    webpackConfig.resolve.extensionAlias = {
      '.cjs': ['.cts', '.cjs'],
      '.js': ['.ts', '.tsx', '.js', '.jsx'],
      '.mjs': ['.mts', '.mjs'],
    }
    return webpackConfig
  },
  turbopack: { root: path.resolve(dirname) },
}

export default withPayload(nextConfig, { devBundleServerPackages: false })
