import { goto } from '$app/navigation';

export type User = {
	token: string;
	user: {
		username: string;
		email: string;
		level: number;
	};
};

function createUserStore() {
	let user: User | undefined = $state();

	const local_user = localStorage.getItem('user');
	if (local_user) {
		try {
			user = JSON.parse(local_user);
		} catch {
			localStorage.removeItem('user');
		}
	}

	return {
		checkLogin(redirect = true) {
			console.log('test1');
			if (user !== undefined) {
				return true;
			}

			console.log('test2');
			if (redirect) {
				goto('/login');
			}

			console.log('test3');
			return false;
		},

		get isLoggedIn() {
			console.log(user);
			return user !== undefined;
		},

		get token() {
			if (user === undefined) {
				throw new Error('User not logged in');
			}

			return user.token;
		},

		set user(new_user: User | undefined) {
			user = new_user;
			if (new_user === undefined) {
				localStorage.removeItem('user');
			} else {
				localStorage.setItem('user', JSON.stringify(new_user));
			}
		},

		get user(): User['user'] {
			if (user === undefined) {
				throw new Error('User not logged in');
			}

			return user.user;
		}
	};
}

export const userStore = createUserStore();
