import { browser } from '$app/environment';
import type { PageLoad } from './$types';
import { env } from '$env/dynamic/public';
import { getSession } from '$lib/state';

const API_HOST = `${browser ? '' : env.BH_CLIENT_INTERNAL_API_HOST}/api/v1`;

interface Job {
	id: Number;
	targetSiteName: string;
	createdTs: string;
	completedTs: string;
	auctionsFound: Number;
	errors: string;
}

interface ScrapeStatusPageData {
	page: number;
	total: number;
	activeTotal: number;
	completeTotal: number;
	limit: number;
	active: Job[];
	complete: Job[];
}

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

	console.log(getSession());
	try {
		const response = await fetch(
			new Request(API_HOST + `/sync${searchParams.toQueryString()}`,
				{
					method: 'GET',
					headers: {
						'bh-session-id': getSession()?.sessionId,
					}
				}

			)

		);
		const { active, complete, activeTotal, completeTotal, total, page } = await response.json();

		return {
			active,
			complete,
			activeTotal,
			completeTotal,
			total,
			page,
			limit
		};
	} catch (e) {
		console.log(e);
		return {
			activeTotal: 0,
			completeTotal: 0,
			active: [],
			complete: [],
			total: 0,
			page: 1,
			limit
		};
	}
}) satisfies PageLoad;

class SearchParameters {
	page: number;
	limit: number;

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

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

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

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

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