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 = "/login") {
			if (user !== undefined) {
				return true;
			}

			if (redirect) {
				goto(redirect);
			}

			return false;
		},

		get isLoggedIn() {
			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();
