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

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

    if (!ae_acct) {
        console.warn(
            `ae Journals [journal_id] +layout.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;
    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 (browser) {
        if (log_lvl)
            console.log(
                `ae_journals journals [journal_id] +layout.ts (Non-Blocking)`
            );

        // OPTIMIZATION: Fire the journal load in the background.
        // The journal module now uses SWR, and components watching IDB
        // will update automatically when the refresh completes.
        journals_func.load_ae_obj_id__journal({
            api_cfg: ae_acct.api,
            journal_id: journal_id,
            inc_entry_li: true,
            enabled: 'enabled',
            hidden: 'all',
            limit: 99,
            try_cache: true,
            log_lvl: 0
        });
    }

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

    return data;
}
