import { signOut, signIn } from 'next-auth/react';
import { errorHandler, requestResponseHandler } from './actionsHandlers';
import {
  BE_AUTH_LOGIN_URL,
  BE_AUTH_REFRESH_JWT_URL,
  BE_AUTH_REGISTER_URL,
  BE_AUTH_PROFILES_URL,
  BE_AUTH_PROFILES_ROLES_URL,
  BE_AUTH_RESET_PASSWORD_URL,
  BE_AUTH_NEW_PASSWORD_URL,
  FE_USERS_LOGIN_URL,
} from '@/utils/Url';
import { PARENT_FILTER } from '@/utils/constants';

/**
 * Login action
 */
export const login = (data) => {
  return signIn('credentials', {
    redirect: false,
    email: data.email,
    password: data.password,
    role_type: data.role_type,
  });
};

/**
 * Login user with API
 */
export const getJWT = (data) => {
  const request = new Request(`${BE_AUTH_LOGIN_URL}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
    credentials: 'include',
  });
  return fetch(request).then(requestResponseHandler).catch(errorHandler);
};
export const refreshJWT = (data) => {
  const request = new Request(`${BE_AUTH_REFRESH_JWT_URL}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
    credentials: 'include',
  });
  return fetch(request).then(requestResponseHandler).catch(errorHandler);
};

/**
 * Disconnects the user after confirming the action.
 * If `NEXT_PUBLIC_USE_FAKE_DATA` environment variable is set to 'true', it will log a fake disconnect and redirect to the login URL.
 * Otherwise, it will call `signOut` from NextAuth.js to handle the logout.
 *
 * @function
 * @name disconnect
 * @returns {void}
 */
export const disconnect = () => {
  signOut({ callbackUrl: FE_USERS_LOGIN_URL });
};

export const fetchProfileRoles = (
  establishment,
  filter = PARENT_FILTER,
  page = '',
  pageSize = ''
) => {
  let url = `${BE_AUTH_PROFILES_ROLES_URL}?filter=${filter}&establishment_id=${establishment}`;
  if (page !== '' && pageSize !== '') {
    url = `${BE_AUTH_PROFILES_ROLES_URL}?filter=${filter}&establishment_id=${establishment}&page=${page}`;
  }
  return fetch(url, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

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

export const deleteProfileRoles = async (id, csrfToken) => {
  const response = await fetch(`${BE_AUTH_PROFILES_ROLES_URL}/${id}`, {
    method: 'DELETE',
    headers: {
      'X-CSRFToken': csrfToken,
    },
    credentials: 'include',
  });

  if (!response.ok) {
    // Extraire le message d'erreur du backend
    const errorData = await response.json();
    const errorMessage =
      errorData?.error ||
      'Une erreur est survenue lors de la suppression du profil.';

    // Jeter une erreur avec le message spécifique
    throw new Error(errorMessage);
  }

  return response.json();
};

export const fetchProfiles = () => {
  return fetch(`${BE_AUTH_PROFILES_URL}`)
    .then(requestResponseHandler)
    .catch(errorHandler);
};

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

export const deleteProfile = (id, csrfToken) => {
  const request = new Request(`${BE_AUTH_PROFILES_URL}/${id}`, {
    method: 'DELETE',
    headers: {
      'X-CSRFToken': csrfToken,
    },
    credentials: 'include',
  });
  return fetch(request).then(requestResponseHandler).catch(errorHandler);
};

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

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

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

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