import type { NextConfig } from 'next';

const securityHeaders = [
  { key: 'Strict-Transport-Security', value: 'max-age=31536000; includeSubDomains' },
  { 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=()' },
];

const nextConfig: NextConfig = {
  allowedDevOrigins: ['192.168.3.3'],
  compress: true,
  poweredByHeader: false,
  reactStrictMode: true,

  transpilePackages: ['@rentaldrivego/types'],

  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'res.cloudinary.com',
      },
    ],
  },

  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';
    const carplaceOrigin =
      process.env.CARPLACE_INTERNAL_URL ?? 'http://carplace:3004';

    return [
      {
        source: '/carplace',
        destination: `${carplaceOrigin}`,
      },
      {
        source: '/carplace/:path*',
        destination: `${carplaceOrigin}/:path*`,
      },
      {
        source: '/dashboard',
        destination: `${dashboardOrigin}/dashboard`,
      },
      {
        source: '/dashboard/:path*',
        destination: `${dashboardOrigin}/dashboard/:path*`,
      },
      {
        source: '/admin',
        destination: `${adminOrigin}/admin`,
      },
      {
        source: '/admin/:path*',
        destination: `${adminOrigin}/admin/:path*`,
      },
    ];
  },
};

export default nextConfig;
