/**
 * URL utilities for consistent base URL handling across the application.
 * Environment-aware: respects NEXT_PUBLIC_APP_URL, falls back to SITE.domain.
 */

import { SITE, type Lang } from '@/lib/config';

/**
 * Get the application base URL, environment-aware.
 * Priority: NEXT_PUBLIC_APP_URL > SITE.domain fallback
 * Ensures no trailing slash for clean URL concatenation.
 */
export function getAppBaseUrl(): string {
  const envUrl = process.env.NEXT_PUBLIC_APP_URL;
  const normalized =
    envUrl && envUrl.startsWith('http')
      ? envUrl
      : envUrl
      ? `https://${envUrl}`
      : `https://${SITE.domain}`;
  return normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;
}

/**
 * Build a full URL for a given path.
 * @param path - The path (can start with / or not)
 * @returns Full URL with base
 */
export function buildUrl(path: string): string {
  const base = getAppBaseUrl();
  const cleanPath = path.startsWith('/') ? path : `/${path}`;
  return `${base}${cleanPath}`;
}

/**
 * Build a canonical URL for a specific page.
 * @param lang - Language code
 * @param path - Optional additional path after language
 */
export function getCanonicalUrl(lang: Lang, path: string = ''): string {
  const cleanPath = path.startsWith('/') ? path : path ? `/${path}` : '';
  return buildUrl(`/${lang}${cleanPath}`);
}

/**
 * Build alternate language URLs for hreflang tags.
 * @param path - The path after the language segment
 */
export function getAlternateUrls(path: string = '') {
  const cleanPath = path.startsWith('/') ? path : path ? `/${path}` : '';
  return {
    'x-default': buildUrl(`/en${cleanPath}`),
    en: buildUrl(`/en${cleanPath}`),
    ar: buildUrl(`/ar${cleanPath}`),
  };
}

/**
 * Check if we're in a production environment.
 */
export function isProduction(): boolean {
  return process.env.NODE_ENV === 'production';
}

/**
 * Check if we're in development environment.
 */
export function isDevelopment(): boolean {
  return process.env.NODE_ENV === 'development';
}
