import logger from '@/utils/logger';
import { BE_DOCUSEAL_DOWNLOAD_TEMPLATE } from '@/utils/Url';

export default function handler(req, res) {
  if (req.method === 'GET') {
    const { slug, establishment_id, apiDocuseal } = req.query;
    logger.debug('slug : ', slug);

    fetch(`${BE_DOCUSEAL_DOWNLOAD_TEMPLATE}/${slug}?establishment_id=${establishment_id}`, {
      method: 'GET',
      headers: {
        'X-Auth-Token': apiDocuseal,
      },
    })
      .then((response) => {
        if (!response.ok) {
          return response.json().then((err) => {
            throw new Error(err.message);
          });
        }
        return response.json();
      })
      .then((data) => {
        logger.debug('Template downloaded successfully:', data);
        res.status(200).json(data);
      })
      .catch((error) => {
        logger.error('Error downloading template:', error);
        res.status(500).json({ error: 'Internal Server Error' });
      });
  } else {
    res.setHeader('Allow', ['GET']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}
