/** @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';

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;
    let ae_acct = data[account_id];

    if (!ae_acct) {
        console.warn(
            `ae Journals [journal_entry_id] +page.ts: Account ${account_id} not found. Initializing ghost acct.`
        );
        ae_acct = {
            api: data.ae_api || {},
            slct: {
                account_id: 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
        const load_journal_entry_obj =
            await 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
            });

        if (!load_journal_entry_obj) {
            console.warn(
                `ae Journals [journal_entry_id] +page.ts: Entry ${journal_entry_id} not found via API or Cache.`
            );
            // 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;
}
