export type ApiClientOptions = {
	basePath: string;
	loginPath?: string;
};

export function createApiClient({ basePath, loginPath = '/login' }: ApiClientOptions) {
	async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
		const headers: Record<string, string> = {
			...((options.headers as Record<string, string>) || {})
		};

		if (options.body && typeof options.body === 'string') {
			headers['Content-Type'] = 'application/json';
		}

		const response = await fetch(`${basePath}${path}`, {
			...options,
			headers,
			credentials: 'include' // sends platform_session cookie
		});

		if (response.status === 401) {
			if (typeof window !== 'undefined') {
				window.location.href = loginPath;
			}
			throw new Error('Unauthorized');
		}

		if (!response.ok) {
			const err = await response.json().catch(() => ({ error: response.statusText }));
			throw new Error(err.error || `HTTP ${response.status}`);
		}

		return response.json();
	}

	return {
		get: <T>(path: string) => request<T>(path),
		post: <T>(path: string, data: unknown) => request<T>(path, { method: 'POST', body: JSON.stringify(data) }),
		patch: <T>(path: string, data: unknown) => request<T>(path, { method: 'PATCH', body: JSON.stringify(data) }),
		put: <T>(path: string, data: unknown) => request<T>(path, { method: 'PUT', body: JSON.stringify(data) }),
		del: <T>(path: string) => request<T>(path, { method: 'DELETE' }),
		// For raw fetch (file uploads etc)
		fetch: (path: string, options: RequestInit = {}) =>
			fetch(`${basePath}${path}`, { ...options, credentials: 'include' })
	};
}

// Platform auth helpers
export const platformAuth = {
	async login(username: string, password: string) {
		const res = await fetch('/api/auth/login', {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ username, password }),
			credentials: 'include'
		});
		return res.json();
	},

	async logout() {
		await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
	},

	async me() {
		const res = await fetch('/api/auth/me', { credentials: 'include' });
		return res.json();
	},

	async isAuthenticated(): Promise<boolean> {
		try {
			const data = await this.me();
			return data.authenticated === true;
		} catch {
			return false;
		}
	}
};
