import { signOut, signIn } from 'next-auth/react';
import { errorHandler, requestResponseHandler } from './actionsHandlers';
import { fetchWithAuth } from '@/utils/fetchWithAuth';
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 fetchWithAuth(url);
};

export const updateProfileRoles = (id, data, csrfToken) => {
  return fetchWithAuth(`${BE_AUTH_PROFILES_ROLES_URL}/${id}`, {
    method: 'PUT',
    headers: { 'X-CSRFToken': csrfToken },
    body: JSON.stringify(data),
  });
};

export const deleteProfileRoles = (id, csrfToken) => {
  return fetchWithAuth(`${BE_AUTH_PROFILES_ROLES_URL}/${id}`, {
    method: 'DELETE',
    headers: { 'X-CSRFToken': csrfToken },
  });
};

export const fetchProfiles = () => {
  return fetchWithAuth(`${BE_AUTH_PROFILES_URL}`);
};

export const createProfile = (data, csrfToken) => {
  return fetchWithAuth(`${BE_AUTH_PROFILES_URL}`, {
    method: 'POST',
    headers: { 'X-CSRFToken': csrfToken },
    body: JSON.stringify(data),
  });
};

export const deleteProfile = (id, csrfToken) => {
  return fetchWithAuth(`${BE_AUTH_PROFILES_URL}/${id}`, {
    method: 'DELETE',
    headers: { 'X-CSRFToken': csrfToken },
  });
};

export const updateProfile = (id, data, csrfToken) => {
  return fetchWithAuth(`${BE_AUTH_PROFILES_URL}/${id}`, {
    method: 'PUT',
    headers: { 'X-CSRFToken': csrfToken },
    body: JSON.stringify(data),
  });
};

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);
};
