import { browser } from '$app/environment';
import { config } from '$lib/config';
import type { Session, SessionIdentity } from '../../app';

export type { Session, SessionIdentity };

const isBrowser = browser;

function createAuthStore() {
	let session = $state<Session | null>(null);
	let checkInProgress = false;

	const isAuthenticated = $derived(Boolean(session?.active));
	const userEmail = $derived(session?.identity?.traits?.email ?? null);
	const userFullName = $derived(
		session?.identity?.traits?.name
			? `${session.identity.traits.name.first ?? ''} ${session.identity.traits.name.last ?? ''}`.trim()
			: null
	);

	async function checkSession(fetchFn?: typeof fetch): Promise<Session | null> {
		const fetchToUse = fetchFn || (isBrowser ? fetch : null);
		if (!fetchToUse) return null;
		if (checkInProgress && !fetchFn) return null;

		if (!fetchFn) checkInProgress = true;

		try {
			const response = await fetchToUse(`${config.kratos.publicUrl}/sessions/whoami`, {
				credentials: 'include',
				headers: {
					Accept: 'application/json'
				}
			});

			if (response.ok) {
				const sessionData = await response.json();
				session = sessionData;
				return sessionData;
			} else {
				session = null;
				return null;
			}
		} catch (error) {
			console.warn('Failed to check session:', error);
			session = null;
			return null;
		} finally {
			if (!fetchFn) checkInProgress = false;
		}
	}

	async function logout(returnTo?: string): Promise<void> {
		if (!isBrowser) return;

		try {
			// Build full URL for return_to parameter
			const returnUrl = returnTo
				? returnTo.startsWith('http')
					? returnTo
					: `${config.app.origin}${returnTo}`
				: config.app.origin;
			const logoutEndpoint = `${config.kratos.publicUrl}/self-service/logout/browser?return_to=${encodeURIComponent(returnUrl)}`;
			const response = await fetch(logoutEndpoint, {
				credentials: 'include'
			});

			if (response.ok) {
				const logoutData = await response.json();
				if (logoutData.logout_url) {
					window.location.href = logoutData.logout_url;
				}
			}
		} catch (error) {
			console.error('Logout failed:', error);
		} finally {
			session = null;
		}
	}

	function redirectToLogin(returnTo?: string): void {
		if (!isBrowser) return;

		const returnUrl = returnTo
			? returnTo.startsWith('http')
				? returnTo
				: `${config.app.origin}${returnTo}`
			: window.location.href;

		window.location.href = `${config.kratos.publicUrl}/self-service/login/browser?return_to=${encodeURIComponent(returnUrl)}`;
	}

	function redirectToRegistration(returnTo?: string): void {
		if (!isBrowser) return;

		const returnUrl = returnTo
			? returnTo.startsWith('http')
				? returnTo
				: `${config.app.origin}${returnTo}`
			: window.location.href;

		window.location.href = `${config.kratos.publicUrl}/self-service/registration/browser?return_to=${encodeURIComponent(returnUrl)}`;
	}

	// Initialize session check on browser
	if (isBrowser) {
		checkSession().catch(() => {
			// Intentionally ignored - error already logged in checkSession
		});
	}

	return {
		get session() {
			return session;
		},
		get isAuthenticated() {
			return isAuthenticated;
		},
		get userEmail() {
			return userEmail;
		},
		get userFullName() {
			return userFullName;
		},
		checkSession,
		logout,
		redirectToLogin,
		redirectToRegistration
	};
}

export const auth = createAuthStore();
