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

import { browser } from '$app/environment';
import { events_func } from '$lib/ae_events/ae_events_functions';

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

    const data = await parent();

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

    data.ae_events_pres_mgmt_event_session_id_page_ts = true;

    const event_session_id = params.session_id;
    if (!event_session_id) {
        console.log(
            `ae events_pres_mgmt session [session_id] +page.ts: The event_session_id was not found in the params!!!`
        );
        error(404, {
            message: 'Session not found'
        });
    }
    ae_acct.slct.event_session_id = event_session_id;

    // Initialize container for the pre-loaded object
    let initial_session_obj = null;

    if (browser) {
        if (log_lvl)
            console.log(`ae_events [session_id] +page.ts (Blocking Refresh)`);

        // STABILITY FIX: Await the load AND capture the result.
        // We pass this direct object to the page to ensure immediate rendering
        // without waiting for IDB/LiveQuery round-trip.
        initial_session_obj = await events_func.load_ae_obj_id__event_session({
            api_cfg: ae_acct.api,
            event_session_id: event_session_id,
            inc_file_li: true,
            inc_presentation_li: true,
            inc_presenter_li: true,
            inc_file_counts: true, // Use richer view so file_count badge is accurate on session detail page
            try_cache: true,
            log_lvl: log_lvl
        });
    }

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

    // Pass the pre-loaded data to the page component
    data.initial_session_obj = initial_session_obj;

    // CRITICAL: SvelteKit does NOT automatically include params in returned data.
    // The page component needs these for liveQuery subscriptions.
    data.params = params;

    return data;
}
