/**
 * Static Asset URL Helper
 *
 * Resolves static asset URLs with content-based hashing for cache invalidation.
 *
 * In development:
 * - Returns unhashed URLs directly (e.g., /static/font.woff)
 * - No manifest lookup needed
 * - Fast iteration with no hash overhead
 *
 * In production:
 * - Returns hashed URLs from manifest (e.g., /static/font.a3f892c1.woff)
 * - Enables immutable cache headers with automatic invalidation
 * - Hash changes when content changes
 *
 * Usage:
 *   import { staticAssetUrl } from '@/utils/staticAssetUrl';
 *
 *   // In JSX
 *   <link rel="preload" href={staticAssetUrl('PPNeueMontreal-Regular.woff')} />
 *
 *   // In components
 *   <img src={staticAssetUrl('hero-bg.jpg')} />
 */

// Import manifest at build time
// In production builds, Next.js will inline this JSON
let manifest: Record<string, string> | null = null;

// Dynamically import manifest in production builds only
// This is wrapped in try-catch to handle build environments where manifest doesn't exist yet
if (process.env.NODE_ENV === 'production') {
  try {
    // eslint-disable-next-line @typescript-eslint/no-require-imports
    manifest = require('@/asset-manifest.json') as Record<string, string>;
  } catch {
    // Manifest not available - will fall back to /static/ paths
    manifest = null;
  }
}

/**
 * Resolves a static asset path to its hashed URL
 *
 * @param filename - The filename relative to /static/ (e.g., 'font.woff')
 * @returns The full path to the asset
 *   - Dev: '/static/font.woff' (unhashed)
 *   - Prod: '/static-p/font.a3f892c1.woff' (hashed with long cache)
 */
export function staticAssetUrl(filename: string): string {
  // Development: serve unhashed files from /static
  if (process.env.NODE_ENV === 'development') {
    return `/static/${filename}`;
  }

  // Production: use manifest for hashed URLs from /static-p
  if (manifest && manifest[filename]) {
    return `/static-p/${manifest[filename]}`;
  }

  // Fallback: asset not in manifest or manifest not loaded
  if (process.env.NODE_ENV === 'production' && !manifest?.[filename]) {
    console.error(`[staticAssetUrl] Asset not found in manifest: ${filename}`);
  }

  return `/static/${filename}`;
}
