/** @type {import('next').NextConfig} */

const { buildSecurityHeaders, normalizeAssetPrefix } = require('../../config/nextSecurityHeaders')

// The storefront proxies /dashboard and /admin to their own Next dev servers.
// Allow those asset-prefix origins so proxied pages can load chunks and HMR.
const dashboardAssetSource = normalizeAssetPrefix(
  process.env.DASHBOARD_ASSET_PREFIX ?? (process.env.NODE_ENV !== 'production' ? 'http://localhost:3001' : undefined),
  '/dashboard',
)
const securityHeaders = buildSecurityHeaders({
  assetSources: [dashboardAssetSource, process.env.ADMIN_ASSET_PREFIX],
})
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'res.cloudinary.com',
      },
    ],
  },
  transpilePackages: ['@rentaldrivego/types'],
  async headers() {
    return [
      {
        source: '/:path*',
        headers: securityHeaders,
      },
    ]
  },
  async redirects() {
    return [
      {
        source: '/dashboard/dashboard',
        destination: '/dashboard',
        permanent: false,
      },
      {
        source: '/dashboard/dashboard/:path*',
        destination: '/dashboard/:path*',
        permanent: false,
      },
    ]
  },
  async rewrites() {
    const dashboardOrigin = process.env.DASHBOARD_INTERNAL_URL ?? 'http://dashboard:3001'
    const adminOrigin = process.env.ADMIN_INTERNAL_URL ?? 'http://admin:3002'

    return [
      // Dashboard has basePath '/dashboard'. The proxy preserves the prefix
      // so the dashboard can strip it and route internally.
      {
        source: '/dashboard',
        destination: `${dashboardOrigin}/dashboard`,
      },
      {
        source: '/dashboard/:path*',
        destination: `${dashboardOrigin}/dashboard/:path*`,
      },
      // Admin routes (also uses basePath)
      {
        source: '/admin',
        destination: `${adminOrigin}/admin`,
      },
      {
        source: '/admin/:path*',
        destination: `${adminOrigin}/admin/:path*`,
      },
    ]
  },
}

module.exports = nextConfig
