import { OwlBoardClient, ValidationError, ApiError } from '@owlboard/owlboard-ts';
import { browser, dev } from '$app/environment';
import { error } from '@sveltejs/kit';

// Import the runes containing the API Key config Here...

const baseUrl: string = browser ? window.location.origin : '';

const getBaseUrl = () => {
	if (!browser) return '';

	if (dev) return 'https://test.owlboard.info';

	return window.location.origin;
};

export const OwlClient = new OwlBoardClient(
	getBaseUrl()
	// API Key Here when ready!!!
);

export function ThrowApiError(e: unknown): never {
	// Handle Request failure
	if (e instanceof TypeError && e.message === 'Failed to fetch') {
		throw error(503, {
			message: 'Unable to connect to the OwlBoard server',
			name: 'NETWORK_ERROR',
			code: 'NETWORK_UNREACHABLE'
		});
	}

	// Map ApiError 'code' values
	if (e instanceof ApiError) {
		console.error(JSON.stringify(e), e.code, 'ERRCODE');
		let status = 500;
		if (e.code === 'AUTH') {
			status = 401;
		} else if (e.code === 'NOT_FOUND') {
			status = 404;
		} else if (e.code === 'RATE_LIMIT') {
			status = 421;
		} else if (e.code === 'NETWORK_DISCONNECTED') {
			status = 503;
		} else if (e.code === 'VALIDATION') {
			status = 400;
		}

		throw error(status, {
			message: e.message || 'An operational error has occurred',
			name: e.name || 'API_ERROR',
			code: e.code || 'UNKNOWN_API_ERROR'
		});
	}

	// Fallback for other error kind
	const genericMessage = e instanceof Error ? e.message : 'An unexpected error occurred.';
	console.log(e);
	throw error(500, {
		message: genericMessage,
		name: 'CRITICAL_ERROR',
		code: 'INTERNAL_ERROR',
		msg: 'UNHANDLED_EXCEPTION'
	});
}

export { ValidationError, ApiError };
