import { headers } from 'next/headers';
import { config } from './config';

/**
 * Get the current base URL from request headers
 * Automatically detects hoerdle.de or hördle.de (xn--hrdle-jua.de)
 */
export async function getBaseUrl(): Promise<string> {
    const headersList = await headers();
    const host = headersList.get('host') || headersList.get('x-forwarded-host') || '';
    
    let domain = config.domain; // Default fallback
    
    if (host) {
        // Extract domain from host (remove port if present)
        const detectedDomain = host.split(':')[0].toLowerCase();
        
        // Map domains
        if (detectedDomain === 'hoerdle.de') {
            domain = 'hoerdle.de';
        } else if (detectedDomain === 'hördle.de' || detectedDomain === 'xn--hrdle-jua.de') {
            domain = 'hördle.de';
        } else {
            // Use detected domain if it's different from default
            domain = detectedDomain;
        }
    }
    
    // Always use HTTPS in production
    const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
    return `${protocol}://${domain}`;
}

/**
 * Get base URL synchronously (for use in non-async contexts)
 * Uses environment variable or config as fallback
 */
export function getBaseUrlSync(): string {
    const domain = process.env.NEXT_PUBLIC_DOMAIN || config.domain;
    const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
    return `${protocol}://${domain}`;
}

