import { env } from '$env/dynamic/private'
import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import type {Exam} from '$lib/data/CMSDataType'
import dayjs from 'dayjs' 
export const load: PageServerLoad = async ({fetch}) => {
	let res = await fetch(env.API_CMS_URL+"/home")
	let info
	if(!res.ok)
	{
		console.log(res.status,"load offline CMS data instead")
		info = (await import('$lib/data/info.json')).default
	}else{
		info = await res.json()
	}
	const {title,subtitle} = info

	res = await fetch(env.API_CMS_URL+"/content/home")
	if(!res.ok){
		console.log(res.status,"load offline home content instead")
		const content = (await import('$lib/data/content/home.html?raw')).default 
		info = {content,image:"/images/pattern.png"}
	}else{
		info = await res.json()
	}
	//throw error(500, 'ไม่สามารถอ่านเนื้อหาหน้าหลักได้');
	const {content,image} = info
	//Inner function reduce code and able to throw here 
	async function loadExam(api_path:string,err_msg:string){
		const res = await fetch(api_path)
		if(!res.ok){
			console.log(res.status,err_msg,res.statusText)
			throw error(res.status, err_msg);
		}
		const exams:Exam[] = await res.json()
		exams.forEach((e)=>{
			e.date = dayjs(e.announcement_startDate).format("DD MMM BBBB")
			e.image = e.image?e.image:"/images/exam_place_holder.png"
		})
		//This page layout require 3 item, patch with empty
		for(let i=exams.length;i<3;i++){
			exams.push({id:"0",title:"",date:"",category:" ",image:"/images/exam_place_holder.png"})
		}
		return exams	
	}
	const qualify_exams = loadExam(env.API_QUALIFYING_URL +"/qualifying?limit=3",'ไม่สามารถอ่านรายการคัดเลือกได้')
	const competitive_exams = loadExam(env.API_COMPETITIVE_URL+"/competitive?limit=3",'ไม่สามารถอ่านรายการสอบแข่งขันได้')

	return {title,subtitle,content,image, qualify_exams,competitive_exams };
};
