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 { path } = req.query;
  if (!path) {
    return res.status(400).json({ error: 'Le paramètre "path" est requis' });
  }

  try {
    const backendUrl = `${BACKEND_URL}/Common/serve-file/?path=${encodeURIComponent(path)}`;

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

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

    const contentType =
      backendRes.headers.get('content-type') || 'application/octet-stream';
    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 (error) {
    return res.status(500).json({ error: 'Erreur lors du téléchargement' });
  }
}
