import {
  BE_SUBSCRIPTION_REGISTRATIONFILE_GROUPS_URL,
  BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_TEMPLATES_URL,
  BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_MASTERS_URL,
  BE_SUBSCRIPTION_REGISTRATION_PARENT_FILE_MASTERS_URL,
  BE_SUBSCRIPTION_REGISTRATION_PARENT_FILE_TEMPLATES_URL,
  FE_API_DOCUSEAL_CLONE_URL,
  FE_API_DOCUSEAL_DOWNLOAD_URL,
  FE_API_DOCUSEAL_GENERATE_TOKEN,
  FE_API_DOCUSEAL_DELETE_URL
} from '@/utils/Url';
import { errorHandler, requestResponseHandler } from './actionsHandlers';

// FETCH requests

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 const fetchRegistrationFileFromGroup = async (groupId) => {
  const response = await fetch(
    `${BE_SUBSCRIPTION_REGISTRATIONFILE_GROUPS_URL}/${groupId}/school_file_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 fetchRegistrationSchoolFileMasters = (id = null) => {
  let url = `${BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_MASTERS_URL}`;
  if (id) {
    url = `${BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_MASTERS_URL}/${id}`;
  }
  const request = new Request(`${url}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  return fetch(request).then(requestResponseHandler).catch(errorHandler);
};

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

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

// CREATE requests

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 const createRegistrationSchoolFileMaster = (data, csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_MASTERS_URL}`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'X-CSRFToken': csrfToken,
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const createRegistrationParentFileMaster = (data, csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_REGISTRATION_PARENT_FILE_MASTERS_URL}`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'X-CSRFToken': csrfToken,
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const createRegistrationSchoolFileTemplate = (data, csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_TEMPLATES_URL}`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'X-CSRFToken': csrfToken,
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const createRegistrationParentFileTemplate = (data, csrfToken) => {
  return fetch(`${BE_SUBSCRIPTION_REGISTRATION_PARENT_FILE_TEMPLATES_URL}`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'X-CSRFToken': csrfToken,
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

// EDIT requests

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 editRegistrationSchoolFileMaster = (fileId, data, csrfToken) => {
  return fetch(
    `${BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_MASTERS_URL}/${fileId}`,
    {
      method: 'PUT',
      body: JSON.stringify(data),
      headers: {
        'X-CSRFToken': csrfToken,
        'Content-Type': 'application/json',
      },
      credentials: 'include',
    }
  )
    .then(requestResponseHandler)
    .catch(errorHandler);
};

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

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

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

// DELETE requests

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 deleteRegistrationSchoolFileMaster = (fileId, csrfToken) => {
  return fetch(
    `${BE_SUBSCRIPTION_REGISTRATION_SCHOOL_FILE_MASTERS_URL}/${fileId}`,
    {
      method: 'DELETE',
      headers: {
        'X-CSRFToken': csrfToken,
      },
      credentials: 'include',
    }
  );
};

export const deleteRegistrationParentFileMaster = (id, csrfToken) => {
  return fetch(
    `${BE_SUBSCRIPTION_REGISTRATION_PARENT_FILE_MASTERS_URL}/${id}`,
    {
      method: 'DELETE',
      headers: {
        'X-CSRFToken': csrfToken,
      },
      credentials: 'include',
    }
  );
};

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

export const deleteRegistrationParentFileTemplate = (id, csrfToken) => {
  return fetch(
    `${BE_SUBSCRIPTION_REGISTRATION_PARENT_FILE_TEMPLATES_URL}/${id}`,
    {
      method: 'DELETE',
      headers: {
        'X-CSRFToken': csrfToken,
      },
      credentials: 'include',
    }
  );
};

// API requests
export const removeTemplate = (templateId, selectedEstablishmentId, apiDocuseal) => {
  return fetch(`${FE_API_DOCUSEAL_DELETE_URL}`, {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      templateId,
      establishment_id :selectedEstablishmentId,
      apiDocuseal
    }),
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

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

export const downloadTemplate = (slug, selectedEstablishmentId, apiDocuseal) => {
  const url = `${FE_API_DOCUSEAL_DOWNLOAD_URL}/${slug}?establishment_id=${selectedEstablishmentId}&apiDocuseal=${apiDocuseal}`;
  return fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const generateToken = (email, id = null, selectedEstablishmentId, apiDocuseal) => {
  return fetch(`${FE_API_DOCUSEAL_GENERATE_TOKEN}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ user_email: email, id, establishment_id :selectedEstablishmentId, apiDocuseal }),
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};
