import { NextRequest, NextResponse } from 'next/server';
import {
  getEmbeddedTranslations,
  translationLocaleFor,
} from '@/lib/localization/embeddedTranslations';

const LOCALIZATION_SERVICE_URL =
  process.env.LOCALIZATION_SERVICE_URL ?? 'http://localhost:4003';

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ locale: string }> },
) {
  const resolved = await params;
  const localeParam = resolved?.locale ?? '';
  if (!localeParam) {
    return NextResponse.json(
      { error: 'Locale is required' },
      { status: 400 },
    );
  }

  try {
    const fetchLocale = translationLocaleFor(localeParam);
    const res = await fetch(
      `${LOCALIZATION_SERVICE_URL}/api/translations/${encodeURIComponent(fetchLocale)}`,
    );

    if (res.ok) {
      const data = await res.json();
      return NextResponse.json(data);
    }
  } catch {
    /* localization-service недоступен */
  }
  return NextResponse.json(getEmbeddedTranslations(localeParam));
}
