const withPWA = require('next-pwa')({
  disable: process.env.NODE_ENV !== 'production',
  dest: 'public',
  register: true,
  skipWaiting: true
})

function buildRemotePatterns() {
  const raw = process.env.NEXT_PUBLIC_DOMAINS_IMAGE || ''
  const patterns = raw.split(' ').filter(Boolean).map(entry => {
    const [hostname, port] = entry.split(':')
    const isLocal = hostname === 'localhost' || hostname === '127.0.0.1'
    const pattern = {protocol: isLocal ? 'http' : 'https', hostname, pathname: '/uploads/**'}
    if (port) {
      pattern.port = port
    }

    return pattern
  })
  if (!raw.includes('localhost')) {
    patterns.push({protocol: 'http', hostname: 'localhost', port: '1337', pathname: '/uploads/**'})
  }

  if (!raw.includes('127.0.0.1')) {
    patterns.push({protocol: 'http', hostname: '127.0.0.1', port: '1337', pathname: '/uploads/**'})
  }

  return patterns
}

module.exports = (withPWA({
  turbopack: {},
  images: {
    remotePatterns: buildRemotePatterns()
  }
}))
