/** @type {import('./$types').LayoutLoad} */
console.log(`ae_l_journals [journal_id] +layout.ts start`);

import { error } from '@sveltejs/kit';
import { browser } from '$app/environment';
import { journals_func } from '$lib/ae_journals/ae_journals_functions';
// import { db_journals, journal_field_li, journal_entry_field_li } from "$lib/ae_journals/db_journals";
// import { load_ae_obj_id } from '$lib/ae_core/core__crud_generic';

export async function load({ params, parent }) {
	const log_lvl: number = 0;

	const data = await parent();
	data.log_lvl = log_lvl;

	const account_id = data.account_id;
	const ae_acct = data[account_id];

	const journal_id = params.journal_id;
	if (!journal_id) {
		console.log(
			`ae_journals journals [journal_id] +page.ts: The journal_id was not found in the params!!!`
		);
		error(404, {
			message: 'Journals - Journal ID not found'
		});
	}
	ae_acct.slct.journal_id = journal_id;
	if (log_lvl) {
		console.log(`ae_journals journals [journal_id] +page.ts: journal_id = `, journal_id);
	}

	if (browser) {
		if (log_lvl) {
			console.log(`ae_journals journals [journal_id] +page.ts: journal_id = `, journal_id);
		}
		// Load journal object
		// let load_journal_obj = load_ae_obj_id({
		//     api_cfg: ae_acct.api,
		//     obj_type: 'journal',
		//     obj_id:  journal_id,
		//     db_instance: db_journals,
		//     db_field_li: journal_field_li,
		//     inc_obj_type_li: ['journal_entry'],
		//     log_lvl: 2
		// });

		const load_journal_obj = await journals_func.load_ae_obj_id__journal({
			api_cfg: ae_acct.api,
			journal_id: journal_id,
			inc_entry_li: true,
			enabled: 'enabled',
			hidden: 'all', // 'not_hidden' to load only visible entries
			limit: 99,
			try_cache: true,
			log_lvl: log_lvl
		});
		// .then((results) => {
		//     if (!results) {
		//         error(404, {
		//             message: 'Journals - Journal not found'
		//         });
		//     } else {
		//         // ae_acct.slct.journal_obj = results;
		//     }
		// })
		// .catch((err) => {
		//     console.error(`Error loading journal object:`, err);
		//     error(500, {
		//         message: 'Journals - Error loading journal object'
		//     });
		// });

		if (!load_journal_obj) {
			error(404, {
				message: 'Journals - Journal Entry not found'
			});
		} else {
			ae_acct.slct.load_journal_obj = load_journal_obj;
		}
	}

	// WARNING: Precaution against shared data between sites.
	data[account_id] = ae_acct;

	return data;
}
