import { NextRequest, NextResponse } from 'next/server';

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

const fallbackLocale = {
  locale: 'en',
  language: 'en',
  region: null,
  countryCode: null,
  timezone: null,
  source: 'fallback' as const,
};

export async function GET(req: NextRequest) {
  try {
    const res = await fetch(`${LOCALIZATION_SERVICE_URL}/api/locale`, {
      headers: {
        'x-forwarded-for': req.headers.get('x-forwarded-for') ?? '',
        'x-real-ip': req.headers.get('x-real-ip') ?? '',
        'user-agent': req.headers.get('user-agent') ?? '',
        'accept-language': req.headers.get('accept-language') ?? '',
      },
    });

    if (!res.ok) return NextResponse.json(fallbackLocale);
    const data = await res.json();
    return NextResponse.json(data);
  } catch {
    return NextResponse.json(fallbackLocale);
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const res = await fetch(`${LOCALIZATION_SERVICE_URL}/api/locale`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-forwarded-for': req.headers.get('x-forwarded-for') ?? '',
        'x-real-ip': req.headers.get('x-real-ip') ?? '',
        'user-agent': req.headers.get('user-agent') ?? '',
        'accept-language': req.headers.get('accept-language') ?? '',
      },
      body: JSON.stringify(body),
    });

    if (!res.ok) return NextResponse.json(fallbackLocale);
    const data = await res.json();
    return NextResponse.json(data);
  } catch {
    return NextResponse.json(fallbackLocale);
  }
}
