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 new Response('Unauthorized', { status: 401 });
  }

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

  const body = await response.arrayBuffer();
  const contentType = response.headers.get('Content-Type') || 'application/octet-stream';
  const disposition =
    response.headers.get('Content-Disposition') ||
    (url.searchParams.get('format') === 'xlsx'
      ? 'attachment; filename="audit-trail-export.xlsx"'
      : 'attachment; filename="audit-trail-export.csv"');

  return new Response(body, {
    status: response.status,
    headers: {
      'Content-Type': contentType,
      'Content-Disposition': disposition,
    },
  });
}
