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

export default function handler(req, res) {
  if (req.method === 'POST') {
    const { templateId, email, is_required, establishment_id, apiDocuseal } = req.body;

    fetch(BE_DOCUSEAL_CLONE_TEMPLATE, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Auth-Token': apiDocuseal,
      },
      body: JSON.stringify({
        templateId,
        email,
        is_required,
        establishment_id,
      }),
    })
      .then((response) => {
        if (!response.ok) {
          return response.json().then((err) => {
            throw new Error(err.message);
          });
        }
        return response.json();
      })
      .then((data) => {
        logger.debug('Template cloned successfully:', data);
        res.status(200).json(data);
      })
      .catch((error) => {
        logger.error('Error cloning template:', error);
        res.status(500).json({ error: 'Internal Server Error' });
      });
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}
