import {
    BE_SUBSCRIPTION_STUDENTS_URL,
    BE_SUBSCRIPTION_CHILDRENS_URL,
    BE_SUBSCRIPTION_REGISTERFORMS_URL,
    BE_SUBSCRIPTION_LAST_GUARDIAN_ID_URL
} from '@/utils/Url';

export const PENDING = 'pending';
export const SUBSCRIBED = 'subscribed';
export const ARCHIVED = 'archived';


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 const fetchRegisterForms = (establishment, filter=PENDING, page='', pageSize='', search = '') => {
    let url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}?filter=${filter}&establishment_id=${establishment}`;
    if (page !== '' && pageSize !== '') {
        url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}?filter=${filter}&establishment_id=${establishment}&page=${page}&search=${search}`;
    }
    return fetch(url, {
      headers: {
        'Content-Type': 'application/json',
      },
    }).then(requestResponseHandler)
  };

export const fetchRegisterForm =  (id) =>{
    return fetch(`${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}`)  // Utilisation de studentId au lieu de codeDI
           .then(requestResponseHandler)
}
export const fetchLastGuardian =  () =>{
    return fetch(`${BE_SUBSCRIPTION_LAST_GUARDIAN_ID_URL}`)
           .then(requestResponseHandler)
}

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


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

export const sendRegisterForm = (id) => {
    const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/send`;
    return fetch(url, {
        headers: {
        'Content-Type': 'application/json',
        },
    }).then(requestResponseHandler)
}

export const resendRegisterForm = (id) => {
    const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/resend`;
    return fetch(url, {
        headers: {
        'Content-Type': 'application/json',
        },
    }).then(requestResponseHandler)

}
export const archiveRegisterForm = (id) => {
    const url = `${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/archive`;
    return fetch(url, {
        method: 'GET',
        headers: {
        'Content-Type': 'application/json',
        },
    }).then(requestResponseHandler)
}

export const fetchStudents = (establishment, id=null) => {
  const url = (id)?`${BE_SUBSCRIPTION_STUDENTS_URL}/${id}`:`${BE_SUBSCRIPTION_STUDENTS_URL}?establishment_id=${establishment}`;
    const request = new Request(
            url,
            {
                method:'GET',
                headers: {
                    'Content-Type':'application/json'
                },
            }
    );
    return fetch(request).then(requestResponseHandler)

};

export const fetchChildren = (id, establishment) =>{
      const request = new Request(
            `${BE_SUBSCRIPTION_CHILDRENS_URL}/${id}?establishment_id=${establishment}`,
            {
                method:'GET',
                headers: {
                    'Content-Type':'application/json'
                },
            }
    );
    return fetch(request).then(requestResponseHandler)
}

export async function getRegisterFormFileTemplate(fileId) {
  const response = await fetch(`${BE_SUBSCRIPTION_REGISTERFORM_FILE_TEMPLATE_URL}/${fileId}`, {
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
    }
  });
  if (!response.ok) {
    throw new Error('Failed to fetch file template');
  }
  return response.json();
}

export const fetchTemplatesFromRegistrationFiles = async (id) => {
  const response = await fetch(`${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}/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();
}