/* eslint-disable no-unused-vars */ import axios, { AxiosResponse } from 'axios'; import { createContext, type Dispatch, type PropsWithChildren, type SetStateAction, useEffect, useState } from 'react'; import * as authHelper from '../_helpers'; import { type AuthModel, type UserModel } from '@/auth'; import { apiConfig } from '@/config/api.config'; import { doSaveLogActivity } from '@/actions/GlobalActions'; const API_URL = apiConfig.service_dashboard; export const LOGIN_URL = `${API_URL}/login`; export const GET_USER_URL = `${API_URL}/user/profile`; interface AuthContextProps { loading: boolean; setLoading: Dispatch>; auth: AuthModel | undefined; saveAuth: (auth: AuthModel | undefined) => void; currentUser: UserModel | undefined; setCurrentUser: Dispatch>; login: (email: string, password: string, token?: string) => Promise; logout: () => void; verify: () => Promise; } const AuthContext = createContext(null); const AuthProvider = ({ children }: PropsWithChildren) => { const [loading, setLoading] = useState(true); const [auth, setAuth] = useState(authHelper.getAuth()); const [currentUser, setCurrentUser] = useState(); const saveAuth = (auth: AuthModel | undefined) => { setAuth(auth); if (auth) { authHelper.setAuth(auth); } else { authHelper.removeAuth(); } }; const login = async (username: string, password: string, token?: string) => { try { const { data: auth } = await axios .post(LOGIN_URL, { username, password }) .then((response) => response.data); const enhancedAuth: AuthModel = { ...auth.token, id: auth.userid, user: auth.user, }; saveAuth(enhancedAuth); setCurrentUser(auth.user); const createActivity = { module: 'Login', description: `Login`, action: 'l' }; doSaveLogActivity(createActivity); } catch (error: any) { console.error('Login error:', error); throw error; } }; const getUser = async () => { let _axios = await axios .get(`${GET_USER_URL}/${authHelper.getAuth()?.user?.id}`) .then((response) => response.data.data); return { data: _axios }; }; const verify = async () => { if (auth) { try { const { data: user } = await getUser(); // Perbarui auth yang sekarang dengan statusbalance saveAuth({ ...auth, }); const createCacheUser = { name: user.name, email: user.email, username: user.username, }; localStorage.setItem('user', JSON.stringify(createCacheUser)); } catch { saveAuth(undefined); setCurrentUser(undefined); } } }; const logout = async () => { const createActivity = { module: 'Logout', description: `Logout`, action: 'O' }; await doSaveLogActivity(createActivity); saveAuth(undefined); setCurrentUser(undefined); }; return ( {children} ); }; export { AuthContext, AuthProvider };