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

interface User {
	username: string;
	role: string;
}

interface AuthState {
	token: string | null;
	user: User | null;
}

/**
 * Auth Store
 * 
 * SECURITY NOTE: Token is stored in localStorage which is vulnerable to XSS attacks.
 * The CSP (Content Security Policy) helps mitigate XSS risks.
 * For production with higher security requirements, consider migrating to httpOnly cookies.
 */
function createAuthStore() {
	// SECURITY: Validate stored data before parsing to prevent XSS via localStorage
	const stored = browser ? localStorage.getItem('auth') : null;
	let initial: AuthState = { token: null, user: null };
	
	if (stored) {
		try {
			const parsed = JSON.parse(stored);
			// Validate structure to prevent injection
			if (parsed && typeof parsed === 'object' && 
			    (parsed.token === null || typeof parsed.token === 'string') &&
			    (parsed.user === null || (typeof parsed.user === 'object' && parsed.user.username && parsed.user.role))) {
				initial = parsed;
			}
		} catch (e) {
			// Invalid stored data, clear it
			if (browser) {
				localStorage.removeItem('auth');
			}
		}
	}

	const { subscribe, set, update } = writable<AuthState>(initial);

	return {
		subscribe,
		login: (token: string, user: User) => {
			const state = { token, user };
			set(state);
			if (browser) {
				localStorage.setItem('auth', JSON.stringify(state));
			}
		},
		logout: () => {
			set({ token: null, user: null });
			if (browser) {
				localStorage.removeItem('auth');
			}
		},
		getToken: () => {
			let token: string | null = null;
			update((s) => (token = s.token));
			return token;
		}
	};
}

export const auth = createAuthStore();
