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

/**
 * Fetches a single Aether object by its ID using the CRUD endpoint.
 * Refactored 2026-01-08 to properly handle unauthenticated lookups (Bootstrap Paradox)
 * and ensure clean header passing to get_object without mutating the global config.
 */
export async function get_ae_obj_id_crud({
    api_cfg,
    no_account_id = false,
    obj_type,
    obj_id,
    use_alt_table = false,
    use_alt_base = false,
    inc = {},
    enabled = 'enabled',
    hidden = 'not_hidden',
    limit = 999999,
    offset = 0,
    data = {},
    headers = {},
    params = {},
    timeout = 60000,
    return_meta = false,
    log_lvl = 0
}: {
    api_cfg: any;
    no_account_id?: boolean;
    obj_type: string;
    obj_id: string;
    use_alt_table?: boolean;
    use_alt_base?: boolean;
    inc?: any;
    enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
    hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
    limit?: number;
    offset?: number;
    data?: any;
    headers?: any;
    params?: key_val;
    timeout?: number;
    return_meta?: boolean;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(`*** get_ae_obj_id_crud() *** Type: ${obj_type} ID: ${obj_id}`);
    }

    // V3 Standard: Unified endpoint for all objects
    const endpoint = `/v3/crud/${obj_type}/${obj_id}`;

    if (log_lvl > 1) {
        console.log('Endpoint:', endpoint);
    }

    const final_params = {
        ...params,
        use_alt_table: use_alt_table,
        use_alt_base: use_alt_base
    };

    const final_headers = { ...headers };

    if (no_account_id) {
        // This instructs get_object to skip account-id requirements
        final_headers['x-no-account-id'] = 'Nothing to See Here';
        final_headers['x-account-id'] = null; // Explicitly null to trigger removal in get_object
    }

    const result = await get_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        headers: final_headers,
        params: final_params,
        timeout: timeout,
        log_lvl: log_lvl,
        return_meta: return_meta
    }).catch(function (error: any) {
        console.error(`API GET CRUD object ID request failed for ${obj_type}/${obj_id}`, error);
        return false;
    });

    if (log_lvl > 1) {
        console.log('GET Object result =', result);
    }

    return result;
}