import { browser } from '$app/environment';
import type { PageLoad } from './$types';

// TODO: change to env var
const API_HOST = `${browser ? '' : 'http://proxy-client-local'}/api/v1`;

interface SearchPageData {
	page: number;
	limit: number;
	found: number;
	total: number;
	query: string;
	results: any[];
}

export const load = (async ({ fetch, url }): Promise<SearchPageData> => {
	const searchParams = new SearchParameters(url);
	const limit = searchParams.getLimit();
	const searchTerm = searchParams.getSearchTerm();

	try {
		// TODO: refactor to one source of truth for all query string building
		const response = await fetch(API_HOST + `/upcoming${searchParams.toQueryString()}`);
		const { page, total, found, results } = (await response.json()) || {};

		// TODO: return found results so we can do upperbound on pagination
		return {
			page,
			limit,
			query: searchTerm,
			found,
			total,
			results
		};
	} catch (e) {
		console.log(e);
		return {
			page: 0,
			limit,
			query: searchTerm,
			found: 0,
			total: 0,
			results: []
		};
	}
}) satisfies PageLoad;

class SearchParameters {
	page: number;
	limit: number;
	searchTerm?: string;

	constructor(url: URL) {
		this.searchTerm = url.searchParams.get('query') || undefined;
		this.page = Number(url.searchParams.get('page') || 1) - 1;
		if (this.page < 0) {
			this.page = 0;
		}

		this.limit = Number(url.searchParams.get('limit') || 64);
		if (this.limit > 128) {
			this.limit = 128;
		} else if (this.limit < 32) {
			this.limit = 32;
		}
	}

	getPage(): number {
		return this.page || 0;
	}

	getSearchTerm(): string {
		return this.searchTerm || '';
	}

	getLimit(): number {
		return this.limit || 64;
	}

	toQueryString(): string {
		const qs = Object.entries(this)
			.filter((t) => t.length > 0 && t[1])
			.map((t) => `${t[0]}=${t[1]}`)
			.join('&');
		return qs === '' ? '' : `?${qs}`;
	}
}
