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

console.log(`ae_idaa_bulletin_board [post_id] +page.ts start`);

import { browser } from '$app/environment';
import { posts_func } from '$lib/ae_posts/ae_posts_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 post_id = params.post_id;

    ae_acct.slct.post_id = post_id;

    if (browser) {
        if (log_lvl) {
            console.log(`ae_idaa_posts posts [post_id] +page.ts: post_id = `, post_id);
        }
        // NOTE: Fire in background — do NOT await. Newly created posts are already in Dexie
        // (saved by create_ae_obj__post), so the liveQuery renders immediately. For direct
        // links or refreshes, the post loads from the API and Dexie updates reactively.
        // Awaiting here blocked the SvelteKit navigation, causing a visible "refresh" delay.
        posts_func
            .load_ae_obj_id__post({
                api_cfg: ae_acct.api,
                post_id: post_id,
                inc_comment_li: true,
                log_lvl: log_lvl
            })
            .then((results) => {
                if (!results) {
                    console.warn(`ae IDAA BB [post_id] +page.ts: Post ${post_id} not found via API or Cache.`);
                }
            });
    }

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

    return data;
}) satisfies PageLoad;
