import { beforeUnloadHandler } from "../app.js"; import { showError } from "../utils/error.js"; async function login(email,pin){ const response = await fetch("/api/users/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, pin }) } ); if (response.status == 420) { window.removeEventListener("beforeunload", beforeUnloadHandler); window.location.replace("/"); } if (response.status == 404) { const errorData = await response.json().catch(() => ({ message: "El usuario no fue encontrado." })); throw new Error(errorData.message); }else if (response.status == 401) { const errorData = await response.json().catch(() => ({ message: "Credenciales incorrectas.", attempts: 0 })); showError(`${errorData.message} Intentos restantes: ${errorData.attempts_remaining || 0}`); throw new Error(errorData.message); } else if (response.status == 429) { const errorData = await response.json().catch(() => ({ message: "Demasiados intentos de inicio de sesión." })); showError(`${errorData.message} Intenta más tarde.`); throw new Error(errorData.message); }else if (response.status != 200) { console.error(response.status, response.statusText); const errorData = await response.json().catch(() => ({ message: "Error al iniciar sesión." })); showError(`${errorData.message}`); throw new Error(errorData.message); } const data = await response.json(); if (!data || !data.data.token) { showError("Error al iniciar sesión, Intenta mas tarde."); throw new Error("Error al iniciar sesión."); } return {data: data.data}; } export { login };