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

export async function GET(_: Request, { params }: { params: Promise<{ id: string }> }) {
  const token = await getProxyAccessToken();
  if (!token) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  const { id } = await params;
  const response = await fetch(`${API_URL}/contacts/${id}`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: 'no-store',
  });

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

export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const token = await getProxyAccessToken();
  if (!token) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  const { id } = await params;
  const body = await request.json();
  const response = await fetch(`${API_URL}/contacts/${id}`, {
    method: 'PATCH',
    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 });
}

export async function DELETE(_: Request, { params }: { params: Promise<{ id: string }> }) {
  const token = await getProxyAccessToken();
  if (!token) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  const { id } = await params;
  const response = await fetch(`${API_URL}/contacts/${id}`, {
    method: 'DELETE',
    headers: { Authorization: `Bearer ${token}` },
    cache: 'no-store',
  });

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