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

const API_BASE = (PUBLIC_API_URL || 'http://localhost:8000');

export interface User {
	email: string;
	name: string;
	picture?: string;
}

export interface AuthState {
	authenticated: boolean;
	user: User | null;
	loading: boolean;
}

function createAuthStore() {
	const { subscribe, set, update } = writable<AuthState>({
		authenticated: false,
		user: null,
		loading: true
	});

	return {
		subscribe,
		async checkAuth() {
			if (!browser) return;

			try {
				const response = await fetch(`${API_BASE}/auth/status`, {
					credentials: 'include'
				});
				const data = await response.json();

				set({
					authenticated: data.authenticated,
					user: data.user || null,
					loading: false
				});

				return data.authenticated;
			} catch (e) {
				console.error('Auth check failed:', e);
				set({
					authenticated: false,
					user: null,
					loading: false
				});
				return false;
			}
		},
		async logout() {
			if (!browser) return;

			try {
				await fetch(`${API_BASE}/auth/logout`, {
					method: 'POST',
					credentials: 'include'
				});
			} catch (e) {
				console.error('Logout failed:', e);
			}

			set({
				authenticated: false,
				user: null,
				loading: false
			});
		},
		setLoading(loading: boolean) {
			update(state => ({ ...state, loading }));
		}
	};
}

export const auth = createAuthStore();
