/** @type {import('./$types').PageLoad} */
import { error } from '@sveltejs/kit';
console.log(`ae_p_journals [journal_entry_id] +page.ts start`);

import { browser } from '$app/environment';
import { journals_func } from '$lib/ae_journals/ae_journals_functions';
import { db_journals, 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 }) {
	// route
	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;
	ae_acct.slct.journal_id = journal_id;

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

	if (browser) {
		if (log_lvl) {
			console.log(
				`ae_journals journals [journal_entry_id] +page.ts: journal_entry_id = `,
				journal_entry_id
			);
		}
		// Load event journal entry object
		// let load_journal_entry_obj = journals_func.load_ae_obj_id__journal_entry({
		//     api_cfg: ae_acct.api,
		//     journal_entry_id:  journal_entry_id,
		//     try_cache: true,
		//     log_lvl: log_lvl
		// });

		const load_journal_entry_obj = load_ae_obj_id({
			api_cfg: ae_acct.api,
			obj_type: 'journal_entry',
			obj_id: journal_entry_id,
			db_instance: db_journals,
			db_field_li: journal_entry_field_li,
			log_lvl: 2
		});

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

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

	return data;
}
