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

/**
 * Time zone lookup — IDB-backed SWR helper.
 *
 * Fetches priority timezones (only_priority=true, ~72 records). Calling this
 * function triggers a background API refresh if IDB is empty or older than
 * 24 hours. Components subscribe to db_lookups.lu_time_zone via liveQuery and
 * receive automatic updates when the refresh completes.
 *
 * Updated 2026-03-23 — replaced $ae_loc + localStorage pattern with IDB + 24h TTL
 */

async function _refresh_lu_time_zone_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_time_zone_background() ***');
    try {
        const result = await api.get_ae_obj_li_for_lu({
            api_cfg,
            for_lu_type: 'time_zone',
            enabled: 'enabled',
            hidden: 'not_hidden',
            only_priority: true, // ~72 priority timezone records
            limit: 1800,
            log_lvl
        });
        if (result?.length) {
            await db_lookups.lu_time_zone.clear();
            await db_lookups.lu_time_zone.bulkPut(result);
            await db_lookups.lu_cache_meta.put({
                lu_type: 'time_zone',
                refreshed_at: Date.now()
            });
            if (log_lvl)
                console.log(
                    `lu_time_zone: saved ${result.length} records to IDB`
                );
        }
    } catch (error) {
        console.error('lu_time_zone refresh failed:', error);
    }
}

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

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

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