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

const GEO_DEVICE_URL =
  process.env.GEO_DEVICE_SERVICE_URL ?? 'http://localhost:4002';

const fallbackContext = (userAgent: string) => ({
  geo: null,
  device: { type: 'unknown' as const },
  browser: { name: 'Unknown', version: '', full: '' },
  os: { name: 'Unknown', version: '', full: '' },
  client: {},
  userAgent,
  requestedAt: new Date().toISOString(),
});

export async function GET(req: NextRequest) {
  try {
    const forwarded = req.headers.get('x-forwarded-for');
    const realIP = req.headers.get('x-real-ip');

    const res = await fetch(`${GEO_DEVICE_URL}/api/context`, {
      headers: {
        'x-forwarded-for': forwarded ?? '',
        'x-real-ip': realIP ?? '',
        'user-agent': req.headers.get('user-agent') ?? '',
        'accept-language': req.headers.get('accept-language') ?? '',
      },
    });

    const data = await res.json();

    if (!res.ok) {
      return NextResponse.json(
        fallbackContext(req.headers.get('user-agent') ?? ''),
      );
    }

    return NextResponse.json(data);
  } catch {
    return NextResponse.json(
      fallbackContext(req.headers.get('user-agent') ?? ''),
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const forwarded = req.headers.get('x-forwarded-for');
    const realIP = req.headers.get('x-real-ip');

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

    const data = await res.json();

    if (!res.ok) {
      return NextResponse.json(
        fallbackContext(req.headers.get('user-agent') ?? ''),
      );
    }

    return NextResponse.json(data);
  } catch {
    return NextResponse.json(
      fallbackContext(req.headers.get('user-agent') ?? ''),
    );
  }
}
