import { NextResponse } from 'next/server';
import { SERVER_API_URL as API_URL } from '../../../lib/server-api';
import { getProxyAccessToken } from '../../../lib/proxy-auth';

function buildUrl(searchParams: URLSearchParams) {
  const query = searchParams.toString();
  return `${API_URL}/contacts${query ? `?${query}` : ''}`;
}

export async function GET(request: Request) {
  const token = await getProxyAccessToken();
  if (!token) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  const url = new URL(request.url);
  const response = await fetch(buildUrl(url.searchParams), {
    headers: {
      Authorization: `Bearer ${token}`,
    },
    cache: 'no-store',
  });

  const payload = await response.json();
  return NextResponse.json(payload, { status: response.status });
}

export async function POST(request: Request) {
  const token = await getProxyAccessToken();
  if (!token) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  const body = await request.json();
  const response = await fetch(`${API_URL}/contacts`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(body),
    cache: 'no-store',
  });

  const payload = await response.json();
  return NextResponse.json(payload, { status: response.status });
}
