export const MAINTENANCE_ACCESS_COOKIE_NAME = 'termi_maintenance_access'

export function sanitizeMaintenanceReturnTo(value: string | null | undefined): string {
  if (!value) {
    return '/'
  }

  const trimmed = value.trim()
  if (!trimmed.startsWith('/') || trimmed.startsWith('//')) {
    return '/'
  }

  try {
    const parsed = new URL(trimmed, 'https://termi.local')
    const nextPath = `${parsed.pathname}${parsed.search}${parsed.hash}`

    if (
      nextPath === '/maintenance' ||
      nextPath.startsWith('/maintenance?') ||
      nextPath.startsWith('/api/maintenance')
    ) {
      return '/'
    }

    return nextPath || '/'
  } catch {
    return '/'
  }
}

export function shouldBypassMaintenance(pathname: string): boolean {
  return (
    pathname === '/maintenance' ||
    pathname.startsWith('/api/maintenance') ||
    pathname === '/healthz' ||
    pathname === '/favicon.ico' ||
    pathname.startsWith('/favicon.') ||
    pathname.startsWith('/apple-touch-icon') ||
    pathname.startsWith('/_astro/') ||
    pathname.startsWith('/_image') ||
    pathname.startsWith('/_img')
  )
}
