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,
  { params }: { params: Promise<{ id: string }> },
) {
  const token = (await cookies()).get(authCookieName)?.value;
  if (!token) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  const { id } = await params;
  const url = new URL(request.url);
  const format = url.searchParams.get('format') === 'xlsx' ? 'xlsx' : 'csv';

  const response = await fetch(`${API_URL}/campaigns/${id}/export?format=${format}`, {
    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') || 'application/octet-stream');
  headers.set(
    'Content-Disposition',
    response.headers.get('Content-Disposition') || `attachment; filename="campaign-report.${format}"`,
  );

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