import { BE_SUBSCRIPTION_REGISTRATIONFILE_GROUPS_URL,
        BE_SUBSCRIPTION_REGISTRATION_TEMPLATES_URL,
        BE_SUBSCRIPTION_REGISTRATION_TEMPLATE_MASTER_URL,
        FE_API_DOCUSEAL_CLONE_URL,
        FE_API_DOCUSEAL_DOWNLOAD_URL
} from '@/utils/Url';

const requestResponseHandler = async (response) => {

  const body = await response.json();
  if (response.ok) {
    return body;
  }
   // Throw an error with the JSON body containing the form errors
  const error = new Error(body?.errorMessage || "Une erreur est survenue");
  error.details = body;
  throw error;
}

export async function fetchRegistrationFileGroups(establishment) {
  const response = await fetch(`${BE_SUBSCRIPTION_REGISTRATIONFILE_GROUPS_URL}?establishment_id=${establishment}`, {
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
    }
  });
  if (!response.ok) {
    throw new Error('Failed to fetch file groups');
  }
  return response.json();
}

export async function createRegistrationFileGroup(groupData, csrfToken) {
  const response = await fetch(`${BE_SUBSCRIPTION_REGISTRATIONFILE_GROUPS_URL}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': csrfToken,
    },
    body: JSON.stringify(groupData),
    credentials: 'include'
  });

  if (!response.ok) {
    throw new Error('Failed to create file group');
  }

  return response.json();
}

export async function deleteRegistrationFileGroup(groupId, csrfToken) {
  const response = await fetch(`${BE_SUBSCRIPTION_REGISTRATIONFILE_GROUPS_URL}/${groupId}`, {
    method: 'DELETE',
    headers: {
      'X-CSRFToken': csrfToken,
    },
    credentials: 'include'
  });

  return response;
}

export const editRegistrationFileGroup = async (groupId, groupData, csrfToken) => {
  const response = await fetch(`${BE_SUBSCRIPTION_REGISTRATIONFILE_GROUPS_URL}/${groupId}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': csrfToken,
    },
    body: JSON.stringify(groupData),
  });

  if (!response.ok) {
    throw new Error('Erreur lors de la modification du groupe');
  }

  return response.json();
};

export const fetchRegistrationFileFromGroup = async (groupId) => {
  const response = await fetch(`${BE_SUBSCRIPTION_REGISTRATIONFILE_GROUPS_URL}/${groupId}/templates`, {
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
    }
  });
  if (!response.ok) {
    throw new Error('Erreur lors de la récupération des fichiers associés au groupe');
  }
  return response.json();
}

export  const fetchRegistrationTemplates = (id = null) => {
  let url =  `${BE_SUBSCRIPTION_REGISTRATION_TEMPLATES_URL}`
  if (id) {
    url = `${BE_SUBSCRIPTION_REGISTRATION_TEMPLATES_URL}/${id}`;
  }
  const request = new Request(
      `${url}`,
      {
          method:'GET',
          headers: {
              'Content-Type':'application/json'
          },
      }
  );
  return fetch(request).then(requestResponseHandler)
};

export const editRegistrationTemplates = (fileId, data, csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_REGISTRATION_TEMPLATES_URL}/${fileId}`, {
    method: 'PUT',
    body: data,
    headers: {
      'X-CSRFToken': csrfToken,
    },
    credentials: 'include',
  })
  .then(requestResponseHandler)
}

export const createRegistrationTemplates = (data,csrfToken) => {

  return fetch(`${BE_SUBSCRIPTION_REGISTRATION_TEMPLATES_URL}`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'X-CSRFToken': csrfToken,
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  })
    .then(requestResponseHandler)
}

export const deleteRegistrationTemplates = (fileId,csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_REGISTRATION_TEMPLATES_URL}/${fileId}`, {
    method: 'DELETE',
    headers: {
      'X-CSRFToken': csrfToken,
    },
    credentials: 'include',
  })
}

export const fetchRegistrationTemplateMaster = (id = null) => {
  let url = `${BE_SUBSCRIPTION_REGISTRATION_TEMPLATE_MASTER_URL}`;
  if(id){
    url = `${BE_SUBSCRIPTION_REGISTRATION_TEMPLATE_MASTER_URL}/${id}`;
  }
  const request = new Request(
        `${url}`,
        {
            method:'GET',
            headers: {
                'Content-Type':'application/json'
            },
        }
    );
    return fetch(request).then(requestResponseHandler)
};

export const createRegistrationTemplateMaster = (data,csrfToken) => {

  return fetch(`${BE_SUBSCRIPTION_REGISTRATION_TEMPLATE_MASTER_URL}`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'X-CSRFToken': csrfToken,
      'Content-Type':'application/json'
    },
    credentials: 'include',
  })
    .then(requestResponseHandler)
}

export const deleteRegistrationTemplateMaster = (fileId,csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_REGISTRATION_TEMPLATE_MASTER_URL}/${fileId}`, {
    method: 'DELETE',
    headers: {
      'X-CSRFToken': csrfToken,
    },
    credentials: 'include',
  })
}

export const editRegistrationTemplateMaster = (fileId, data, csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_REGISTRATION_TEMPLATE_MASTER_URL}/${fileId}`, {
    method: 'PUT',
    body: JSON.stringify(data),
    headers: {
      'X-CSRFToken': csrfToken,
      'Content-Type':'application/json'
    },
    credentials: 'include',
  })
  .then(requestResponseHandler)
}

export const cloneTemplate = (templateId, email, is_required) => {
  return fetch(`${FE_API_DOCUSEAL_CLONE_URL}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      templateId,
      email,
      is_required
    })
  })
  .then(requestResponseHandler)
}

export const downloadTemplate = (slug) => {
  return fetch(`${FE_API_DOCUSEAL_DOWNLOAD_URL}/${slug}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    }
  })
  .then(requestResponseHandler)
}