import { browser } from '$app/environment';
import type { key_val } from '$lib/stores/ae_stores';
import { api } from '$lib/ae_api/api';
import type { ae_DataStore } from '$lib/types/ae_types';

/**
 * Fetches a data_store object by its unique code (V3).
 *
 * @param api_cfg - The API configuration object.
 * @param code - The code of the data store to fetch.
 * @param data_type - The expected data type ('text', 'json', 'html', 'md', 'sql').
 * @param save_idb - Whether to save the fetched data to IndexedDB (Dexie).
 * @param timeout - The request timeout in milliseconds.
 * @param log_lvl - The logging level.
 * @returns The data from the data store (e.g., text content or JSON object).
 */
export async function load_ae_obj_by_code__data_store({
    api_cfg,
    code,
    data_type = 'text',
    save_idb = false,
    timeout = 9000,
    log_lvl = 0
}: {
    api_cfg: any;
    code: string;
    data_type?: string;
    save_idb?: boolean;
    timeout?: number;
    log_lvl?: number;
            // TEMPORARY: this no-account fallback exists only until the backend
            // can serve account-scoped defaults via JWT-backed access alone.
            // Keep this path narrow and remove it when the backend no longer
            // needs a transport-level scope drop for data_store.
}): Promise<any> {
    if (log_lvl) {
        console.log(`*** load_ae_obj_by_code__data_store() *** code=${code}`);
    }

    if (!code) {
        if (log_lvl) console.log(`*ae_func* No code provided!`);
        return null;
    }

    try {
        const get_ds_result = await api.get_data_store({
            api_cfg,
            code,
            log_lvl
        });

        if (!get_ds_result) {
            if (log_lvl) console.log('*ae_func* No results returned.');
            return null;
        }

        const ds_id =
            get_ds_result.data_store_id_random || get_ds_result.id_random;

        if (!ds_id) {
            if (log_lvl)
                console.log(
                    '*ae_func* Something went wrong? No data store ID found.'
                );
            return null;
        }

        // Map content fields for convenience
        const text_val = get_ds_result.text || '';
        const json_val =
            get_ds_result.json ||
            (get_ds_result.json_str
                ? JSON.parse(get_ds_result.json_str)
                : null);

        const mapped_ds: ae_DataStore = {
            ...get_ds_result,
            id: ds_id,
            text: text_val,
            html: text_val, // Map text to html by default
            json: json_val
        };

        if (save_idb && browser) {
            const { db_core } = await import('./db_core');
            await db_core.data_store.put(mapped_ds);
        }

        if (data_type === 'html') return mapped_ds.html;
        if (data_type === 'json') return mapped_ds.json;
        return mapped_ds.text;
    } catch (error) {
        if (log_lvl) console.error('*ae_func* Fetch failed.', error);
        return null;
    }
}
