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

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

import { error } from '@sveltejs/kit';
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 = 1;

    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 Bulletin Board +page.ts: Account ${account_id} not found in parent data. Initializing ghost acct.`);
        ae_acct = {
            api: data.ae_api || {},
            slct: {
                account_id: account_id
            }
        };
    }

    if (browser) {
        const load_post_obj_li = posts_func.load_ae_obj_li__post({
            api_cfg: ae_acct.api,
            for_obj_type: 'account',
            for_obj_id: account_id,
            inc_comment_li: false,
            enabled: 'enabled',
            hidden: 'not_hidden',
            limit: 19,
            order_by_li: { updated_on: 'DESC', created_on: 'DESC' },
            try_cache: true,
            log_lvl: log_lvl
        }).then(posts => {
            // REVIEW AGAIN: The backend now supports filtering out archived posts based on the 'archive_on' field.
            // Workaround: V3 Search does not permit 'archive_on' field yet.
            // Filter locally for posts that are not archived yet.
            const now = new Date();
            return (posts || []).filter((p: any) => !p.archive_on || new Date(p.archive_on) > now);
        });
        if (log_lvl) {
            console.log(`load_post_obj_li = `, load_post_obj_li);
        }
        ae_acct.slct.post_obj_li = load_post_obj_li;
    }

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

    return data;
}) satisfies PageLoad;
