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}/users/export${url.search}`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: 'no-store',
  });
  const csv = await response.text();

  return new NextResponse(csv, {
    status: response.status,
    headers: {
      'Content-Type': 'text/csv; charset=utf-8',
      'Content-Disposition': 'attachment; filename="users-export.csv"',
    },
  });
}
