import { NextRequest, NextResponse } from 'next/server';
import { getStorefrontLanguages, isAdminApiConfigured } from '@/lib/shopware-admin';

export const dynamic = 'force-dynamic';

/**
 * GET /api/languages
 *
 * Returns the storefront's selectable languages, derived from the sales-channel
 * DOMAINS configured in admin (not the channel's assigned-languages list). A
 * language appears here only if a domain was created for it, so the frontend
 * language switcher mirrors exactly what's reachable by URL.
 *
 *   { languages: [{ languageId, name, localeCode, url }] }
 *
 * Server-side proxy so Admin API credentials never reach the browser. Returns
 * an empty list (200) when admin isn't configured so the UI degrades quietly.
 */
export async function GET(request: NextRequest) {
  if (!isAdminApiConfigured()) {
    return NextResponse.json({ languages: [] });
  }
  try {
    const host = request.headers.get('host') || '';
    const proto =
      request.headers.get('x-forwarded-proto') ||
      (host.startsWith('localhost') ? 'http' : 'https');
    const languages = await getStorefrontLanguages(proto === 'https' ? 'https' : 'http');
    return NextResponse.json(
      { languages },
      { headers: { 'Cache-Control': 'no-store' } }
    );
  } catch {
    return NextResponse.json({ languages: [] });
  }
}
