import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

const PRODUCTION_DOMAIN = 'rentaldrivego.com'
const DEFAULT_SLUG = process.env.NEXT_PUBLIC_COMPANY_SLUG ?? 'demo'

/**
 * Resolve the company slug from the request host.
 *
 * Production:  {slug}.rentaldrivego.com  →  slug
 * Development: localhost / 127.0.0.1     →  DEFAULT_SLUG (env var fallback)
 * Staging/preview URLs that don't match the production domain also fall back.
 */
function resolveSlug(host: string | null): string {
  if (!host) return DEFAULT_SLUG

  // Strip port number if present
  const hostname = host.split(':')[0]

  // Production subdomain: slug.rentaldrivego.com
  if (hostname.endsWith(`.${PRODUCTION_DOMAIN}`)) {
    const subdomain = hostname.slice(0, hostname.length - PRODUCTION_DOMAIN.length - 1)
    // Ignore www / bare domain
    if (subdomain && subdomain !== 'www') return subdomain
  }

  return DEFAULT_SLUG
}

export function middleware(request: NextRequest) {
  const host = request.headers.get('host')
  const slug = resolveSlug(host)

  const response = NextResponse.next()

  // Forward the slug as a request header so server components can read it
  // via `headers()` without needing cookies.
  response.headers.set('x-company-slug', slug)

  // Also set a short-lived cookie so client components / route handlers
  // can pick it up without another round-trip.
  response.cookies.set('x-company-slug', slug, {
    path: '/',
    maxAge: 60, // 1 minute – intentionally short; re-derived on every request
    sameSite: 'lax',
    httpOnly: false, // readable from JS for client-side fetches
  })

  return response
}

export const config = {
  matcher: [
    /*
     * Match all request paths except:
     * - _next/static  (static files)
     * - _next/image   (image optimisation)
     * - favicon.ico
     * - public folder files (png, svg, jpg, …)
     */
    '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:png|jpg|jpeg|gif|svg|ico|webp|woff2?|ttf|otf|css|js)$).*)',
  ],
}
