/** @type {import('./$types').LayoutLoad} */
console.log(`Events - [event_id] +layout.ts`);

import { error } from '@sveltejs/kit';
import { browser } from '$app/environment';
import { events_func } from '$lib/ae_events/ae_events_functions';

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

    const data = await parent();
    // console.log(`ae events_pres_mgmt event [event_id] +page.ts data:`, data);
    data.log_lvl = log_lvl;

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

    if (!ae_acct) {
        console.warn(
            `ae Events - [event_id] +layout.ts: Account ${account_id} not found in data. Initializing ghost acct.`
        );
        ae_acct = {
            api: data.ae_api || {},
            slct: {
                account_id: account_id
            }
        };
    }

    const event_id = params.event_id;
    if (!event_id) {
        console.log(
            `ae Events - [event_id] +layout.ts: The event_id was not found in the params.event_id!!!`
        );
        error(404, {
            message: 'Events Pres Mgmt - Event ID not found'
        });
    }

    ae_acct.slct.event_id = event_id;

    if (browser) {
        if (log_lvl)
            console.log(`ae_events [event_id] +layout.ts (Non-Blocking)`);

        // OPTIMIZATION: Fire the event load in the background without 'await'.
        // The event module uses SWR, so this will:
        // 1. Check Dexie cache and update IDB instantly.
        // 2. Fetch fresh data from API and update IDB.
        // 3. Components using LiveQuery (like lq__event_obj) will react automatically.
        events_func.load_ae_obj_id__event({
            api_cfg: ae_acct.api,
            event_id: event_id,
            // inc_file_li: false, // Changing from true 2026-02-04
            // inc_location_li: false, // Changing from true 2026-02-04
            // inc_session_li: false,
            // inc_template_li: false,
            log_lvl: log_lvl // Keep background quiet unless debugging
        });
    }

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

    return data;
}
