import { browser } from '$app/environment';
import { env } from '$env/dynamic/public';
import { writable } from 'svelte/store';

const API_HOST = `${browser ? '' : env.BH_CLIENT_INTERNAL_API_HOST}/api/v1`;

interface SessionInfo {
	sessionId?: string;
	account?: {
		id: string;
		email: string;
		role: 'BIDDER' | 'USER' | 'ADMINISTRATOR' | 'ANONYMOUS';
		createdTs: string;
	};
}

export const getSession = () => {
	const strSession = localStorage.getItem('bh-session');
	if (strSession) {
		const data = JSON.parse(strSession);
		if (data?.sessionId) {
			return data;
		}
	}

	return null;
}


export const session = writable<SessionInfo>(undefined, (set) => {
	const session = getSession();
	if (session) {
		set(session);
	}
});

interface LoginAction {
	email: string;
	password: string;
}

export const loginAction = async ({ email, password }: LoginAction): Promise<SessionInfo> => {
	try {
		const sessionStr = localStorage.getItem('bh-session');
		if (sessionStr) {
			const data = JSON.parse(sessionStr);
			if (data.sessionId) {
				console.log('already authenticated');
				session.set(data);
				return data;
			}

			localStorage.removeItem('bh-session');
		}

		const response = await fetch(
			new Request(`${API_HOST}/user`, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					email,
					password
				})
			})
		);

		const data = await response.json();
		console.log(data);

		if (data.sessionId) {
			localStorage.setItem('bh-session', JSON.stringify(data));
			return data;
		}

		console.trace("got this on login attempt:", data);
	} catch (e) {
		console.error(e);
	}

	return {};
};

interface RegisterAction {
	email: string;
	password: string;
	role?: string;
}
export const registerAction = async ({ email, password, role }: RegisterAction) => {
	try {
		const response = await fetch(
			new Request(`${API_HOST}/user`, {
				method: 'PUT',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					email,
					password,
					role: role || 'USER'
				})
			})
		);

		const data = await response.json();
		console.log(data);
	} catch (e) {
		console.error(e);
	}
};

export const logoutAction = () => {
	localStorage.removeItem('bh-session');
	session.set({});
};
