import type { PageLoad } from './$types';

console.log(`ae_p_idaa_events [event_id] +page.ts start`);

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

export const load = (async ({ 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 IDAA Recovery Meeting [event_id] +page.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;

    ae_acct.slct.event_id = event_id;

    if (browser) {
        if (log_lvl) {
            console.log(
                `ae_idaa_events events [event_id] +page.ts: event_id = `,
                event_id
            );
        }
        // Load event object
        const load_event_obj = await events_func.load_ae_obj_id__event({
            api_cfg: ae_acct.api,
            event_id: event_id,
            log_lvl: log_lvl
        });
        // .then((results) => {
        //     if (!results) {
        //         error(404, {
        //             message: 'IDAA Recovery Meetings - Event not found'
        //         });
        //     } else {
        //         // ae_acct.slct.event_obj = results;
        //     }
        // });

        if (log_lvl) {
            console.log(`load_event_obj = `, load_event_obj);
        }

        if (!load_event_obj) {
            console.warn(
                `ae IDAA Recovery Meeting [event_id] +page.ts: Event ${event_id} not found via API or Cache.`
            );
        } else {
            ae_acct.slct.event_obj = load_event_obj;
        }
    }

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

    return data;
}) satisfies PageLoad;
