import type { key_val } from '$lib/stores/ae_stores';
import { api } from '$lib/ae_api/api';

import { db_save_ae_obj_li__ae_obj } from '$lib/ae_core/core__idb_dexie';
import { db_events } from '$lib/ae_events/db_events';
import type { ae_EventExhibit } from '$lib/types/ae_types';

const ae_promises: key_val = {};

// --- PROPERTIES TO SAVE ---
export const properties_to_save_exhibit = [
    'id',
    'event_exhibit_id',
    'event_id',
    'code',
    'name',
    'description',
    'staff_passcode',
    'data_json',
    'leads_api_access',
    'leads_custom_questions_json',
    'leads_device_sm_qty',
    'leads_device_lg_qty',
    'license_max',
    'license_li_json',
    'cfg_json',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    'tmp_sort_1',
    'tmp_sort_2'
];

/**
 * Robust Property Processor (Aether UI V3)
 * Handles ID aliasing and ID clobbering guards.
 */
async function _process_generic_props<T extends Record<string, any>>({
    obj_li,
    obj_type,
    log_lvl = 0,
    specific_processor
}: {
    obj_li: T[];
    obj_type: string;
    log_lvl?: number;
    specific_processor?: (obj: T) => Promise<T> | T;
}): Promise<T[]> {
    if (!obj_li || obj_li.length === 0) return [];

    const processed_obj_li: T[] = [];

    for (const original_obj of obj_li) {
        let processed_obj = { ...original_obj };

        // 1. Random ID Aliasing (Triple-ID Pattern)
        for (const key in processed_obj) {
            if (key.endsWith('_random') && processed_obj[key]) {
                const newKey = key.slice(0, -7);
                // Guard: Only overwrite if the target is null/undefined
                if (!processed_obj[newKey]) {
                    (processed_obj as any)[newKey] = processed_obj[key];
                }
            }
        }

        // 2. Primary Key Mapping (Dexie compatible)
        const randomIdKey = `${obj_type}_id_random`;
        const baseIdKey = `${obj_type}_id`;

        // Prioritize the base ID field as the primary source of truth
        if (processed_obj[baseIdKey]) {
            (processed_obj as any).id = String(processed_obj[baseIdKey]);
        } else if (processed_obj[randomIdKey]) {
            (processed_obj as any).id = String(processed_obj[randomIdKey]);
        }

        // 3. Metadata & Sorting Computation
        const group = processed_obj.group ?? '0';
        const priority = processed_obj.priority ? 1 : 0;
        const sort = processed_obj.sort ?? '0';
        const updated = processed_obj.updated_on ?? processed_obj.created_on;
        const name = processed_obj.name ?? '';

        // Guard: Prevent literal "undefined" string from showing in description
        if ((processed_obj as any).description === 'undefined') {
            (processed_obj as any).description = '';
        }

        (processed_obj as any).tmp_sort_1 =
            `${group}_${priority}_${sort}_${updated}`;
        (processed_obj as any).tmp_sort_2 =
            `${group}_${priority}_${sort}_${name}_${updated}`;

        if (specific_processor) {
            processed_obj = await Promise.resolve(
                specific_processor(processed_obj)
            );
        }

        processed_obj_li.push(processed_obj as T);
    }

    return processed_obj_li;
}

export async function process_ae_obj__exhibit_props({
    obj_li,
    log_lvl = 0
}: {
    obj_li: any[];
    log_lvl?: number;
}) {
    return _process_generic_props({
        obj_li,
        obj_type: 'event_exhibit',
        log_lvl
    });
}

/**
 * Load Single Exhibit (SWR Pattern)
 */
export async function load_ae_obj_id__event_exhibit({
    api_cfg,
    exhibit_id,
    view = 'default',
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    exhibit_id: string;
    view?: string;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventExhibit | null> {
    const start_time = performance.now();
    if (log_lvl) {
        console.log(
            `🔎 [Trace] load_ae_obj_id__event_exhibit: START (id=${exhibit_id}, try_cache=${try_cache})`
        );
    }

    // 1. FAST PATH: Return cached data immediately
    if (try_cache) {
        try {
            const cached = await db_events.exhibit.get(exhibit_id);
            if (cached) {
                const elapsed = (performance.now() - start_time).toFixed(2);
                if (log_lvl)
                    console.log(
                        `✅ [Trace] load_ae_obj_id: CACHE HIT at ${elapsed}ms. Returning stale exhibit shell.`
                    );

                // Background refresh (non-blocking)
                _refresh_exhibit_id_background({
                    api_cfg,
                    exhibit_id,
                    view,
                    try_cache,
                    log_lvl: log_lvl > 1 ? log_lvl : 0
                });
                return cached;
            }
        } catch (e) {
            if (log_lvl)
                console.error(
                    `❌ [Trace] load_ae_obj_id: Cache access error:`,
                    e
                );
        }
    }

    // 2. SLOW PATH: Wait for API
    return await _refresh_exhibit_id_background({
        api_cfg,
        exhibit_id,
        view,
        try_cache,
        log_lvl
    });
}

async function _refresh_exhibit_id_background({
    api_cfg,
    exhibit_id,
    view,
    try_cache,
    log_lvl
}: any) {
    const start_time = performance.now();
    if (typeof navigator !== 'undefined' && !navigator.onLine) return null;
    try {
        if (log_lvl)
            console.log(
                `📡 [Trace] _refresh_exhibit_id: API Fetching id=${exhibit_id}`
            );
        const result = await api.get_ae_obj({
            api_cfg,
            obj_type: 'event_exhibit',
            obj_id: exhibit_id,
            view,
            log_lvl
        });

        if (result) {
            const processed = await process_ae_obj__exhibit_props({
                obj_li: [result],
                log_lvl
            });
            const processed_obj = processed[0];
            const elapsed = (performance.now() - start_time).toFixed(2);

            if (log_lvl)
                console.log(
                    `📦 [Trace] _refresh_exhibit_id: Received from API at ${elapsed}ms`
                );

            if (try_cache) {
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_events,
                    table_name: 'exhibit',
                    obj_li: [processed_obj],
                    properties_to_save: properties_to_save_exhibit,
                    log_lvl
                });
            }
            return processed_obj;
        }
    } catch (e) {
        if (log_lvl)
            console.error(
                `❌ [Trace] _refresh_exhibit_id: API error for id=${exhibit_id}:`,
                e
            );
    }
    return null;
}

/**
 * Load Collection of Exhibits (SWR Pattern)
 */
export async function load_ae_obj_li__event_exhibit({
    api_cfg,
    event_id,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 100,
    offset = 0,
    order_by_li = [
        { priority: 'DESC' },
        { sort: 'DESC' },
        { name: 'ASC' },
        { updated_on: 'DESC' }
    ],
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id: string;
    enabled?: 'enabled' | 'all' | 'not_enabled';
    hidden?: 'hidden' | 'all' | 'not_hidden';
    view?: string;
    limit?: number;
    offset?: number;
    order_by_li?: any;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventExhibit[]> {
    const start_time = performance.now();
    if (log_lvl) {
        console.log(
            `🔎 [Trace] load_ae_obj_li__event_exhibit: START (event=${event_id}, try_cache=${try_cache})`
        );
    }

    if (try_cache) {
        try {
            const cached_li = await db_events.exhibit
                .where('event_id')
                .equals(event_id)
                .toArray();

            if (cached_li && cached_li.length > 0) {
                const elapsed = (performance.now() - start_time).toFixed(2);
                if (log_lvl)
                    console.log(
                        `✅ [Trace] load_ae_obj_li: CACHE HIT at ${elapsed}ms (${cached_li.length} items).`
                    );

                // Background refresh (non-blocking)
                _refresh_exhibit_li_background({
                    api_cfg,
                    event_id,
                    enabled,
                    hidden,
                    view,
                    limit,
                    offset,
                    order_by_li,
                    try_cache,
                    log_lvl: log_lvl > 1 ? log_lvl : 0
                });
                return cached_li;
            }
        } catch (e) {
            if (log_lvl)
                console.error(
                    `❌ [Trace] load_ae_obj_li: Cache access error:`,
                    e
                );
        }
    }

    return await _refresh_exhibit_li_background({
        api_cfg,
        event_id,
        enabled,
        hidden,
        view,
        limit,
        offset,
        order_by_li,
        try_cache,
        log_lvl
    });
}

async function _refresh_exhibit_li_background({
    api_cfg,
    event_id,
    enabled,
    hidden,
    view,
    limit,
    offset,
    order_by_li,
    try_cache,
    log_lvl
}: any) {
    const start_time = performance.now();
    if (typeof navigator !== 'undefined' && !navigator.onLine) return [];
    try {
        if (log_lvl)
            console.log(
                `📡 [Trace] _refresh_exhibit_li: API Fetching exhibits for event=${event_id}`
            );
        const result_li = await api.get_ae_obj_li({
            api_cfg,
            obj_type: 'event_exhibit',
            for_obj_type: 'event',
            for_obj_id: event_id,
            enabled,
            hidden,
            view,
            limit,
            offset,
            order_by_li,
            log_lvl
        });

        if (result_li) {
            const processed = await process_ae_obj__exhibit_props({
                obj_li: result_li,
                log_lvl
            });
            const elapsed = (performance.now() - start_time).toFixed(2);
            if (log_lvl)
                console.log(
                    `📦 [Trace] _refresh_exhibit_li: Received ${processed.length} items from API at ${elapsed}ms.`
                );

            if (try_cache) {
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_events,
                    table_name: 'exhibit',
                    obj_li: processed,
                    properties_to_save: properties_to_save_exhibit,
                    log_lvl
                });
            }
            return processed;
        }
    } catch (e) {
        if (log_lvl)
            console.error(`❌ [Trace] _refresh_exhibit_li: API error:`, e);
    }
    return [];
}

/**
 * Exhibit Create (V3)
 */
export async function create_ae_obj__exhibit({
    api_cfg,
    event_id,
    data_kv,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id: string;
    data_kv: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventExhibit | null> {
    const result = await api.create_nested_obj({
        api_cfg,
        parent_type: 'event',
        parent_id: event_id,
        child_type: 'event_exhibit',
        fields: { ...data_kv },
        log_lvl
    });

    if (result) {
        const processed = await process_ae_obj__exhibit_props({
            obj_li: [result],
            log_lvl
        });
        const processed_obj = processed[0];
        if (try_cache) {
            await db_save_ae_obj_li__ae_obj({
                db_instance: db_events,
                table_name: 'exhibit',
                obj_li: [processed_obj],
                properties_to_save: properties_to_save_exhibit,
                log_lvl
            });
        }
        return processed_obj;
    }
    return null;
}

/**
 * Exhibit Update (V3)
 */
export async function update_ae_obj__exhibit({
    api_cfg,
    event_id,
    exhibit_id,
    data_kv,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id: string;
    exhibit_id: string;
    data_kv: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventExhibit | null> {
    const result = await api.update_nested_obj({
        api_cfg,
        parent_type: 'event',
        parent_id: event_id,
        child_type: 'event_exhibit',
        child_id: exhibit_id,
        fields: data_kv,
        log_lvl
    });

    if (result) {
        const processed = await process_ae_obj__exhibit_props({
            obj_li: [result],
            log_lvl
        });
        const processed_obj = processed[0];
        if (try_cache) {
            await db_save_ae_obj_li__ae_obj({
                db_instance: db_events,
                table_name: 'exhibit',
                obj_li: [processed_obj],
                properties_to_save: properties_to_save_exhibit,
                log_lvl
            });
        }
        return processed_obj;
    }
    return null;
}

/**
 * Exhibit Search (V3 Standardized)
 */
export async function search__exhibit({
    api_cfg,
    event_id,
    fulltext_search_qry_str = null,
    enabled = 'enabled',
    hidden = 'not_hidden',
    priority = 'all',
    view = 'default',
    order_by_li = { name: 'ASC' },
    limit = 100,
    offset = 0,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id: string;
    fulltext_search_qry_str?: string | null;
    enabled?: 'enabled' | 'all' | 'not_enabled';
    hidden?: 'hidden' | 'all' | 'not_hidden';
    priority?: 'all' | 'priority' | 'not_priority';
    view?: string;
    order_by_li?: any;
    limit?: number;
    offset?: number;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventExhibit[]> {
    if (log_lvl) {
        console.log(
            `*** search__exhibit() *** event_id=${event_id} ft=${fulltext_search_qry_str}`
        );
    }

    const search_query: any = {
        q: fulltext_search_qry_str || '',
        and: [{ field: 'event_id', op: 'eq', value: event_id }]
    };

    if (enabled === 'enabled')
        search_query.and.push({ field: 'enable', op: 'eq', value: 1 });
    else if (enabled === 'not_enabled')
        search_query.and.push({ field: 'enable', op: 'eq', value: 0 });

    if (hidden === 'hidden')
        search_query.and.push({ field: 'hide', op: 'eq', value: 1 });
    else if (hidden === 'not_hidden')
        search_query.and.push({ field: 'hide', op: 'eq', value: 0 });

    if (priority === 'priority')
        search_query.and.push({ field: 'priority', op: 'eq', value: 1 });
    else if (priority === 'not_priority')
        search_query.and.push({ field: 'priority', op: 'eq', value: 0 });

    try {
        const result_li = await api.search_ae_obj({
            api_cfg,
            obj_type: 'event_exhibit',
            search_query,
            enabled,
            hidden,
            view,
            order_by_li,
            limit,
            offset,
            log_lvl
        });

        if (result_li && Array.isArray(result_li)) {
            const processed = await process_ae_obj__exhibit_props({
                obj_li: result_li,
                log_lvl
            });
            if (try_cache) {
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_events,
                    table_name: 'exhibit',
                    obj_li: processed,
                    properties_to_save: properties_to_save_exhibit,
                    log_lvl
                });
            }
            return processed;
        }
    } catch (error: any) {
        console.error('search__exhibit V3 Request failed.', error);
    }

    return [];
}
