import type { key_val } from '$lib/stores/ae_stores';
import { post_object } from './api_post_object';

interface SearchAeObjV3Params {
    api_cfg: any;
    obj_type: string;
    search_query: any; // Complex SearchQuery object: { q: string, and: [], or: [] }
    enabled?: 'all' | 'enabled' | 'not_enabled';
    hidden?: 'all' | 'hidden' | 'not_hidden';
    view?: string;
    for_obj_type?: string;
    for_obj_id?: string;
    order_by_li?:
        | Record<string, 'ASC' | 'DESC'>
        | Record<string, 'ASC' | 'DESC'>[]
        | null;
    limit?: number;
    offset?: number;
    delay_ms?: number;
    params?: key_val;
    headers?: any;
    log_lvl?: number;
}

export async function search_ae_obj({
    api_cfg,
    obj_type,
    search_query,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    for_obj_type,
    for_obj_id,
    order_by_li = null,
    limit = 100,
    offset = 0,
    delay_ms = 0,
    params = {},
    headers = {},
    log_lvl = 0
}: SearchAeObjV3Params) {
    const endpoint = `/v3/crud/${obj_type}/search`;

    // Hybrid search: Standard filters passed as query params
    const query_params: key_val = {
        enabled,
        hidden,
        view,
        limit,
        offset,
        ...params
    };

    if (for_obj_type) query_params['for_obj_type'] = for_obj_type;
    if (for_obj_id) query_params['for_obj_id'] = for_obj_id;
    if (order_by_li) query_params['order_by_li'] = JSON.stringify(order_by_li);
    if (delay_ms > 0) query_params['delay_ms'] = delay_ms;

    // Serialize any complex objects in the query params (e.g. ft_qry, lk_qry)
    for (const key in query_params) {
        if (
            typeof query_params[key] === 'object' &&
            query_params[key] !== null
        ) {
            query_params[key] = JSON.stringify(query_params[key]);
        }
    }

    if (log_lvl) {
        console.log('*** search_ae_obj ***');
        console.log('Endpoint:', endpoint);
        console.log('Params:', query_params);
        console.log('Search Query:', search_query);
    }

    // Note: search_query is sent in the BODY via POST
    return await post_object({
        api_cfg,
        endpoint,
        params: query_params,
        headers,
        data: search_query,
        log_lvl
    });
}
