import { getToken } from 'next-auth/jwt';

const BACKEND_URL = process.env.NEXT_PUBLIC_API_URL;

export default async function handler(req, res) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const token = await getToken({
    req,
    secret: process.env.AUTH_SECRET,
    cookieName: 'n3wtschool_session_token',
  });
  if (!token?.token) {
    return res.status(401).json({ error: 'Non authentifié' });
  }

  const { studentId } = req.query;
  if (!studentId) {
    return res
      .status(400)
      .json({ error: 'Le paramètre "studentId" est requis' });
  }

  try {
    const backendUrl = `${BACKEND_URL}/Subscriptions/registerForms/${encodeURIComponent(studentId)}/pdf`;

    const backendRes = await fetch(backendUrl, {
      headers: {
        Authorization: `Bearer ${token.token}`,
        Connection: 'close',
      },
    });

    if (!backendRes.ok) {
      return res.status(backendRes.status).json({
        error: `Erreur backend: ${backendRes.status}`,
      });
    }

    const contentType =
      backendRes.headers.get('content-type') || 'application/pdf';
    const contentDisposition = backendRes.headers.get('content-disposition');

    res.setHeader('Content-Type', contentType);
    if (contentDisposition) {
      res.setHeader('Content-Disposition', contentDisposition);
    }

    const buffer = Buffer.from(await backendRes.arrayBuffer());
    return res.send(buffer);
  } catch {
    return res
      .status(500)
      .json({ error: 'Erreur lors de la génération du PDF' });
  }
}
