import type { key_val } from '$lib/stores/ae_stores';
import { get_object } from './api_get_object';

interface GetDataStoreV3Params {
    api_cfg: any;
    code: string;
    for_type?: string | null;
    for_id?: string | null;
    no_account_id?: boolean;
    log_lvl?: number;
}

/**
 * Get a Data Store object by its human-friendly code (V3)
 * Uses hierarchical fallback logic (Specific -> Account -> Global).
 * TEMPORARY: the global fallback is a stopgap until the backend can
 * serve account-scoped defaults via JWT-backed access only.
 * Path: GET /v3/data_store/code/{code}
 */
export async function get_data_store({
    api_cfg,
    code,
    for_type = null,
    for_id = null,
    no_account_id = false,
    log_lvl = 0
}: GetDataStoreV3Params): Promise<any> {
    if (log_lvl) {
        console.log(
            `*** get_data_store() *** code=${code} no_account_id=${no_account_id}`
        );
    }

    const endpoint = `/v3/data_store/code/${code}`;
    const params: key_val = {};
    if (for_type) params['for_type'] = for_type;
    if (for_id) params['for_id'] = for_id;

    const headers: key_val = {};
    if (no_account_id) {
        // TEMPORARY: keep this narrow global-default escape hatch until the
        // backend can answer the data_store request with account-scoped JWT
        // access only.
        headers['x-no-account-id'] = 'Nothing to See Here';
    }

    return await get_object({
        api_cfg,
        endpoint,
        params,
        headers,
        log_lvl
    });
}
