/** @type {import('./$types').PageLoad} */
import { error } from '@sveltejs/kit';
import { browser } from '$app/environment';
console.log(`ae core person [person_id] +page.ts: start`);

import { core_func } from '$lib/ae_core/ae_core_functions';

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

    const data = await parent();
    // console.log(`ae core person [person_id] +page.ts data:`, data);
    data.log_lvl = log_lvl;

    const account_id = data.account_id;
    // Use spread syntax to create a shallow copy and avoid mutating the shared parent data structure.
    // We specifically clone 'slct' because we will be mutating it below.
    const ae_acct = { ...data[account_id] };
    ae_acct.slct = { ...ae_acct.slct };

    // console.log(`ae_acct = `, ae_acct);

    const person_id = params.person_id;
    // console.log(`person_id = `, person_id);
    if (!person_id) {
        console.log(
            `ae core person [person_id] +page.ts: The person_id was not found in the params!!!`
        );
        error(404, {
            message: 'Person not found'
        });
    }

    ae_acct.slct.person_id = person_id;

    if (browser) {
        // OPTIMIZATION: Fire the refresh in the background.
        // The Person View UI uses LiveQuery/Dexie and will update
        // automatically once this background task finishes.
        core_func.load_ae_obj_id__person({
            api_cfg: ae_acct.api,
            person_id: person_id,
            try_cache: true
        });
    }

    return {
        ...data,
        [account_id]: ae_acct
    };
}
