import ApiService from "@/services/ApiService";

const baseUrl = "tokens";

export const createTokens = async (params) => {
  try {
    const response = await ApiService.post(`${baseUrl}/create`, params);
    return {
      token: response.data.data,
      user: response.data.user || null,
      success: true,
    };
  } catch (error) {
    const data = error.response?.data;
    if (data?.errors) {
      return {
        success: false,
        error: data.errors,
      };
    }
    const message = data?.message;
    if (message) {
      return {
        success: false,
        error: { email: [message] },
      };
    }
    return {
      error: { password: ['No se pudo iniciar sesión. Revisa tu conexión.'] },
      success: false,
    };
  }
};


/** Revoca el token Bearer actual (POST /tokens/logout, Sanctum). */
export const logoutCurrentToken = async () => {
  await ApiService.post(`${baseUrl}/logout`);
};

export const expireTokens = async (idToken) => {
  try {
    const response = await ApiService.delete(`${baseUrl}/${idToken}`);
    return {
      token: response.data.data,
      success: true,
    };
  } catch (error) {
    return {
      error: error.response.data.errors,
      success: false,
    };
  }
};

export const permissions = async () => {
  const response = await ApiService.get(`${baseUrl}/permissions`);
  const data = response.data;
  if (!data || typeof data !== 'object') {
    throw new Error('Respuesta de permisos inválida');
  }
  return data;
};

export const changePw = async (params) => {
  try {
    const response = await ApiService.post(`${baseUrl}/pw`, params);
    return {
      token: response.data.data,
      success: true,
    };
  } catch (error) {
    return {
      error: error.response.data.errors,
      success: false,
    };
  }
};

export const savePw = async (params) => {
    const response = await ApiService.post(`${baseUrl}/savepw`, params);
    return response.data.data;
};

export const getPwUuid = async (params) => {
  const response = await ApiService.post(`${baseUrl}/getpwuuid`, params);
  return response.data.data;
};