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

console.log(`ae_p_idaa_archives [archive_id] +page.ts start`);

import { browser } from '$app/environment';
import { archives_func } from '$lib/ae_archives/ae_archives_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;
    const ae_acct = data[account_id];

    const archive_id = params.archive_id;

    ae_acct.slct.archive_id = archive_id;

    if (browser) {
        if (log_lvl) {
            console.log(
                `ae_idaa_archives archives [archive_id] +page.ts: archive_id = `,
                archive_id
            );
        }
        // NOTE: Fire in background — do NOT await. Newly created archives are already in Dexie
        // (saved by create_ae_obj__archive), so the liveQuery renders immediately. For direct
        // links or refreshes, the archive loads from the API and Dexie updates reactively.
        // Awaiting here blocked the SvelteKit navigation, causing a visible "refresh" delay.
        archives_func
            .load_ae_obj_id__archive({
                api_cfg: ae_acct.api,
                archive_id: archive_id,
                inc_content_li: true,
                enabled: 'enabled',
                hidden: 'all', // 'not_hidden' to load only visible entries
                limit: 99,
                log_lvl: log_lvl
            })
            .then((results) => {
                if (!results) {
                    console.warn(`ae IDAA Archives [archive_id] +page.ts: Archive ${archive_id} not found via API or Cache.`);
                }
            });
    }

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

    return data;
}) satisfies PageLoad;
