import { api } from '$lib/ae_api/api';
import { db_lookups, LOOKUP_TTL_MS } from '$lib/ae_core/db_lookups';

/**
 * Country lookup — IDB-backed SWR helper.
 *
 * Calling this function triggers a background API refresh if IDB is empty or
 * older than 24 hours. The function returns immediately without awaiting the
 * refresh. Components subscribe to db_lookups.lu_country via liveQuery and
 * receive automatic updates when the refresh completes.
 *
 * Updated 2026-03-23 — replaced localStorage pattern with IDB + 24h TTL
 */

async function _refresh_lu_country_background({
    api_cfg,
    log_lvl = 0
}: {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    api_cfg: any;
    log_lvl?: number;
}) {
    if (log_lvl) console.log('*** _refresh_lu_country_background() ***');
    try {
        const result = await api.get_ae_obj_li_for_lu({
            api_cfg,
            for_lu_type: 'country',
            enabled: 'enabled',
            hidden: 'not_hidden',
            limit: 275,
            log_lvl
        });
        if (result?.length) {
            await db_lookups.lu_country.clear();
            await db_lookups.lu_country.bulkPut(result);
            await db_lookups.lu_cache_meta.put({
                lu_type: 'country',
                refreshed_at: Date.now()
            });
            if (log_lvl)
                console.log(
                    `lu_country: saved ${result.length} records to IDB`
                );
        }
    } catch (error) {
        console.error('lu_country refresh failed:', error);
    }
}

export async function load_ae_obj_li__country({
    api_cfg,
    log_lvl = 0
}: {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    api_cfg: any;
    log_lvl?: number;
}) {
    if (log_lvl) console.log('*** load_ae_obj_li__country() ***');

    const count = await db_lookups.lu_country.count();
    const meta = await db_lookups.lu_cache_meta.get('country');
    const is_stale = !meta || Date.now() - meta.refreshed_at > LOOKUP_TTL_MS;

    if (count === 0 || is_stale) {
        // Fire-and-forget — liveQuery subscribers receive updates when IDB is written
        _refresh_lu_country_background({ api_cfg, log_lvl });
    } else if (log_lvl) {
        console.log(
            `lu_country: IDB fresh (${count} records), skipping refresh`
        );
    }
}
