import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { authCookieName } from '../../../../lib/auth';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api';

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

  const url = new URL(request.url);
  const response = await fetch(`${API_URL}/contacts/export${url.search ? url.search : ''}`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: 'no-store',
  });

  const buffer = await response.arrayBuffer();
  const headers = new Headers();
  headers.set('Content-Type', response.headers.get('Content-Type') || 'text/csv; charset=utf-8');
  headers.set(
    'Content-Disposition',
    response.headers.get('Content-Disposition') || 'attachment; filename="contacts-directory.csv"',
  );

  return new NextResponse(buffer, {
    status: response.status,
    headers,
  });
}
