import { env as privateEnv } from '$env/dynamic/private';
import { env as publicEnv } from '$env/dynamic/public';
import type { LayoutServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import { mapFooterData, mapHeaderData } from '$lib/mapping/strapiMapping.svelte.js';
import type { StrapiFooterResponse, StrapiHomepageResponse } from '$lib/types/strapi';

export const load: LayoutServerLoad = async () => {
	const query = new URLSearchParams({
		// Profile: category 'shared', component 'profile', relation 'profile', sub-field 'image'
		'populate[components][on][shared.profile][populate][profile][populate]': 'image',

		// Project: category 'shared', component 'project', relation 'project', sub-relation 'entries'
		'populate[components][on][shared.project][populate][project][populate]': 'entries',

		// Skill: category 'shared', component 'skill', relation 'skill', sub-relation 'entries'
		'populate[components][on][shared.skill][populate][skill][populate]': 'entries',

		// Contact: category 'shared', component 'contact', relation 'contact'
		'populate[components][on][shared.contact][populate]': 'contact'
	}).toString();

	const requestInit: RequestInit = {
		method: 'GET',
		headers: {
			'Content-Type': 'application/json',
			Authorization: `Bearer ${privateEnv.STRAPI_API_KEY}`
		}
	};

	const [homepageResponse, footerResponse] = await Promise.allSettled([
		fetch(`${publicEnv.PUBLIC_STRAPI_URL}/api/homepage?${query}`, requestInit),
		fetch(`${publicEnv.PUBLIC_STRAPI_URL}/api/footer`, requestInit)
	]);

	if (
		homepageResponse.status === 'rejected' ||
		footerResponse.status === 'rejected' ||
		!homepageResponse.value.ok ||
		!footerResponse.value.ok
	) {
		throw error(500, 'Failed to connect to the CMS');
	}

	const [homepageData, footerData]: [StrapiHomepageResponse, StrapiFooterResponse] =
		await Promise.all([homepageResponse.value.json(), footerResponse.value.json()]);

	return {
		title: homepageData.data.title,
		header: mapHeaderData(homepageData),
		components: homepageData.data.components,
		footer: mapFooterData(footerData)
	};
};
