/** @type {import('next').NextConfig} */
const toStoragePattern = (rawUrl) => {
  try {
    const u = new URL(rawUrl.replace(/\/api\/v1\/?$/, ''))
    return {
      protocol: u.protocol.replace(':', ''),
      hostname: u.hostname,
      ...(u.port ? { port: u.port } : {}),
      pathname: '/storage/**',
    }
  } catch {
    return null
  }
}

const storagePatterns = [
  process.env.API_INTERNAL_URL ?? 'http://localhost:4000',
  process.env.API_URL,
  process.env.NEXT_PUBLIC_API_URL,
]
  .filter(Boolean)
  .map(toStoragePattern)
  .filter(Boolean)
  .filter((p, i, arr) => arr.findIndex((q) => q.hostname === p.hostname && q.port === p.port) === i)

const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'res.cloudinary.com',
      },
      ...storagePatterns,
    ],
  },
  transpilePackages: ['@rentaldrivego/types'],
  async rewrites() {
    const apiOrigin = (process.env.API_INTERNAL_URL ?? process.env.API_URL ?? 'http://localhost:4000').replace(/\/api\/v1\/?$/, '')
    return [
      {
        source: '/api/:path*',
        destination: `${apiOrigin}/api/:path*`,
      },
    ]
  },
}

module.exports = nextConfig
