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

const API = process.env.NEXT_PUBLIC_API_URL ?? 'http://127.0.0.1:3000';

interface RouteParams {
  params: Promise<{ id: string }>;
}

export async function GET(_request: NextRequest, { params }: RouteParams) {
  const { id } = await params;
  const cookie = _request.headers.get('cookie') ?? '';
  try {
    const res = await fetch(`${API}/users/${id}/addresses`, {
      headers: { Cookie: cookie },
      cache: 'no-store',
    });
    const body = await res.json().catch(() => ({ items: [] }));
    return NextResponse.json(body, { status: res.status });
  } catch {
    return NextResponse.json({ items: [] }, { status: 502 });
  }
}

export async function POST(request: NextRequest, { params }: RouteParams) {
  const { id } = await params;
  const cookie = request.headers.get('cookie') ?? '';
  const payload = await request.text();
  try {
    const res = await fetch(`${API}/users/${id}/addresses`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Cookie: cookie },
      body: payload,
      cache: 'no-store',
    });
    const body = await res.json().catch(() => ({}));
    return NextResponse.json(body, { status: res.status });
  } catch {
    return NextResponse.json({ error: 'Proxy error' }, { status: 502 });
  }
}