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

/**
 * Country subdivision lookup — IDB-backed SWR helper.
 *
 * Calling this function triggers a background API refresh if IDB is empty or
 * older than 24 hours. Components subscribe to db_lookups.lu_country_subdivision
 * 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_subdivision_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_subdivision_background() ***');
    try {
        const result = await api.get_ae_obj_li_for_lu({
            api_cfg,
            for_lu_type: 'country_subdivision',
            enabled: 'enabled',
            hidden: 'not_hidden',
            limit: 3500,
            log_lvl
        });
        if (result?.length) {
            await db_lookups.lu_country_subdivision.clear();
            await db_lookups.lu_country_subdivision.bulkPut(result);
            await db_lookups.lu_cache_meta.put({
                lu_type: 'country_subdivision',
                refreshed_at: Date.now()
            });
            if (log_lvl)
                console.log(
                    `lu_country_subdivision: saved ${result.length} records to IDB`
                );
        }
    } catch (error) {
        console.error('lu_country_subdivision refresh failed:', error);
    }
}

export async function load_ae_obj_li__country_subdivision({
    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_subdivision() ***');

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

    if (count === 0 || is_stale) {
        _refresh_lu_country_subdivision_background({ api_cfg, log_lvl });
    } else if (log_lvl) {
        console.log(
            `lu_country_subdivision: IDB fresh (${count} records), skipping refresh`
        );
    }
}
