import { BehaviorSubject } from 'rxjs';

import { fetchWrapper } from '@/helpers/fetch-wrapper';

const userSubject = new BehaviorSubject(typeof window !== 'undefined' && JSON.parse(localStorage.getItem('user')));

export const userService = {
    user: userSubject.asObservable(),
    get userValue() { return userSubject.value },
    login,
    logout,
    register,
};

async function login(email, password) {
    const user = await fetchWrapper.post('/api/users/authenticate', { email, password });

    userSubject.next(user);
    localStorage.setItem('user', JSON.stringify(user));
}

function logout() {
    localStorage.removeItem('user');
    userSubject.next(null);
    window.location.href = "/"; 
}

async function register(user) {
    await fetchWrapper.post(`/api/users/register`, user);
}

async function isLogged() {
     return (!userService.userValue) ? (false):(true); 
}




