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_EventExhibitTracking } from '$lib/types/ae_types';

const ae_promises: key_val = {};

// --- PROPERTIES TO SAVE ---
export const properties_to_save_exhibit_tracking = [
    'id',
    'event_exhibit_tracking_id',
    // 'event_exhibit_tracking_id_random',
    'event_exhibit_id',
    // 'event_exhibit_id_random',
    'event_badge_id',
    // 'event_badge_id_random',
    'event_person_id',
    // 'event_person_id_random',
    'external_person_id',
    'exhibitor_notes',
    'responses_json',
    'data_json',
    'event_exhibit_name',
    'event_badge_title_names',
    'event_badge_given_name',
    'event_badge_family_name',
    'event_badge_designations',
    'event_badge_full_name',
    'event_badge_full_name_override',
    'event_badge_professional_title',
    'event_badge_professional_title_override',
    'event_badge_affiliations',
    'event_badge_affiliations_override',
    'event_badge_email',
    'event_badge_email_override',
    'event_badge_location',
    'event_badge_location_override',
    'event_badge_country',
    '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 to prevent clobbering clean IDs
                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.event_badge_full_name ?? '';

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

        (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_tracking_props({
    obj_li,
    log_lvl = 0
}: {
    obj_li: any[];
    log_lvl?: number;
}) {
    return _process_generic_props({
        obj_li,
        obj_type: 'event_exhibit_tracking',
        log_lvl
    });
}

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

    // 1. FAST PATH: Return cached data immediately
    if (try_cache) {
        try {
            const cached =
                await db_events.exhibit_tracking.get(exhibit_tracking_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 lead shell.`
                    );

                // Background refresh (non-blocking)
                _refresh_tracking_id_background({
                    api_cfg,
                    exhibit_tracking_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_tracking_id_background({
        api_cfg,
        exhibit_tracking_id,
        view,
        try_cache,
        log_lvl
    });
}

async function _refresh_tracking_id_background({
    api_cfg,
    exhibit_tracking_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_tracking_id: API Fetching id=${exhibit_tracking_id}`
            );
        const result = await api.get_ae_obj({
            api_cfg,
            obj_type: 'event_exhibit_tracking',
            obj_id: exhibit_tracking_id,
            view,
            log_lvl
        });

        if (result) {
            const processed = await process_ae_obj__exhibit_tracking_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_tracking_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_tracking',
                    obj_li: [processed_obj],
                    properties_to_save: properties_to_save_exhibit_tracking,
                    log_lvl
                });
            }
            return processed_obj;
        }
    } catch (e) {
        if (log_lvl)
            console.error(
                `❌ [Trace] _refresh_tracking_id: API error for id=${exhibit_tracking_id}:`,
                e
            );
    }
    return null;
}

/**
 * Load Collection of Leads (SWR Pattern)
 */
export async function load_ae_obj_li__event_exhibit_tracking({
    api_cfg,
    exhibit_id,
    enabled = 'enabled',
    hidden = 'all',
    view = 'default',
    limit = 100,
    offset = 0,
    order_by_li = [
        { priority: 'DESC' },
        { sort: 'DESC' },
        { created_on: 'DESC' }
    ],
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    exhibit_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_EventExhibitTracking[]> {
    const start_time = performance.now();
    if (log_lvl) {
        console.log(
            `🔎 [Trace] load_ae_obj_li__event_exhibit_tracking: START (exhibit=${exhibit_id}, try_cache=${try_cache})`
        );
    }

    if (try_cache) {
        try {
            const cached_li = await db_events.exhibit_tracking
                .where('event_exhibit_id')
                .equals(exhibit_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_tracking_li_background({
                    api_cfg,
                    exhibit_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_tracking_li_background({
        api_cfg,
        exhibit_id,
        enabled,
        hidden,
        view,
        limit,
        offset,
        order_by_li,
        try_cache,
        log_lvl
    });
}

async function _refresh_tracking_li_background({
    api_cfg,
    exhibit_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_tracking_li: API Fetching leads for exhibit=${exhibit_id}`
            );
        const result_li = await api.get_ae_obj_li({
            api_cfg,
            obj_type: 'event_exhibit_tracking',
            for_obj_type: 'event_exhibit',
            for_obj_id: exhibit_id,
            enabled,
            hidden,
            view,
            limit,
            offset,
            order_by_li,
            log_lvl
        });

        if (result_li) {
            const processed = await process_ae_obj__exhibit_tracking_props({
                obj_li: result_li,
                log_lvl
            });
            const elapsed = (performance.now() - start_time).toFixed(2);
            if (log_lvl)
                console.log(
                    `📦 [Trace] _refresh_tracking_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_tracking',
                    obj_li: processed,
                    properties_to_save: properties_to_save_exhibit_tracking,
                    log_lvl
                });
            }
            return processed;
        }
    } catch (e) {
        if (log_lvl)
            console.error(`❌ [Trace] _refresh_tracking_li: API error:`, e);
    }
    return [];
}

/**
 * Lead Capture (V3)
 */
export async function create_ae_obj__exhibit_tracking({
    api_cfg,
    exhibit_id,
    event_badge_id,
    external_person_id,
    group,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    exhibit_id: string;
    event_badge_id: string;
    external_person_id: string;
    group?: string;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventExhibitTracking | null> {
    const result = await api.create_nested_obj({
        api_cfg,
        parent_type: 'event_exhibit',
        parent_id: exhibit_id,
        child_type: 'event_exhibit_tracking',
        fields: {
            event_badge_id: event_badge_id,
            external_person_id,
            group
        },
        log_lvl
    });

    if (result) {
        const processed = await process_ae_obj__exhibit_tracking_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_tracking',
                obj_li: [processed_obj],
                properties_to_save: properties_to_save_exhibit_tracking,
                log_lvl
            });
        }
        return processed_obj;
    }
    return null;
}

/**
 * Lead Update (V3)
 */
export async function update_ae_obj__exhibit_tracking({
    api_cfg,
    exhibit_id,
    exhibit_tracking_id,
    data,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    exhibit_id: string;
    exhibit_tracking_id: string;
    data: any;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventExhibitTracking | null> {
    const result = await api.update_nested_obj({
        api_cfg,
        parent_type: 'event_exhibit',
        parent_id: exhibit_id,
        child_type: 'event_exhibit_tracking',
        child_id: exhibit_tracking_id,
        fields: data,
        log_lvl
    });

    if (result) {
        const processed = await process_ae_obj__exhibit_tracking_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_tracking',
                obj_li: [processed_obj],
                properties_to_save: properties_to_save_exhibit_tracking,
                log_lvl
            });
        }
        return processed_obj;
    }
    return null;
}

/**
 * Export exhibit tracking (leads) to CSV/XLSX.
 *
 * V3 Action endpoint: GET /v3/action/event_exhibit/{exhibit_id}/tracking_export
 * Backend must return the file as a binary response with appropriate Content-Disposition.
 *
 * Columns expected in the export (all denormalized onto the tracking record):
 *   event_exhibit_tracking_id, created_on, updated_on,
 *   event_exhibit_name,
 *   event_badge_full_name, event_badge_email, event_badge_professional_title,
 *   event_badge_affiliations, event_badge_location, event_badge_country,
 *   external_person_id (captured by), exhibitor_notes,
 *   responses_json (flattened — one column per custom question code),
 *   priority, enable, hide
 */
export async function download_export__event_exhibit_tracking({
    api_cfg,
    exhibit_id,
    file_type = 'CSV',
    filename = 'leads_export.csv',
    log_lvl = 0
}: {
    api_cfg: any;
    exhibit_id: string;
    file_type?: string;
    filename?: string;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(
            `*** download_export__event_exhibit_tracking() *** exhibit_id=${exhibit_id}`
        );
    }

    const endpoint = `/v3/action/event_exhibit/${exhibit_id}/tracking_export`;
    const params: key_val = {
        file_type,
        return_file: 'true' // V3 convention: string 'true' for bool query flags
    };

    return await api.get_object({
        api_cfg,
        endpoint,
        params,
        return_blob: true,
        filename,
        auto_download: true,
        log_lvl
    });
}

/**
 * Lead Search (V3 Standardized)
 */
export async function search__exhibit_tracking({
    api_cfg,
    event_id,
    event_exhibit_id,
    fulltext_search_qry_str = null,
    qry_group = null,
    qry_external_person_id = null,
    qry_badge_id = null,
    enabled = 'enabled',
    hidden = 'all',
    view = 'default',
    order_by_li = { created_on: 'DESC' },
    limit = 100,
    offset = 0,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id: string | undefined;
    event_exhibit_id: string | undefined;
    fulltext_search_qry_str?: string | null;
    qry_group?: string | null;
    qry_external_person_id?: string | null;
    qry_badge_id?: string | null;
    enabled?: 'enabled' | 'all' | 'not_enabled';
    hidden?: 'hidden' | 'all' | 'not_hidden';
    view?: string;
    order_by_li?: any;
    limit?: number;
    offset?: number;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventExhibitTracking[]> {
    if (log_lvl) {
        console.log(
            `*** search__exhibit_tracking() *** exhibit_id=${event_exhibit_id} ft=${fulltext_search_qry_str}`
        );
    }

    if (!event_id || !event_exhibit_id) return [];

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

    if (qry_group)
        search_query.and.push({ field: 'group', op: 'eq', value: qry_group });
    if (qry_external_person_id)
        search_query.and.push({
            field: 'external_person_id',
            op: 'eq',
            value: qry_external_person_id
        });
    if (qry_badge_id)
        search_query.and.push({
            field: 'event_badge_id',
            op: 'eq',
            value: qry_badge_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 });

    try {
        const result_li = await api.search_ae_obj({
            api_cfg,
            obj_type: 'event_exhibit_tracking',
            for_obj_type: 'event_exhibit',
            for_obj_id: event_exhibit_id,
            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_tracking_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_tracking',
                    obj_li: processed,
                    properties_to_save: properties_to_save_exhibit_tracking,
                    log_lvl
                });
            }
            return processed;
        }
    } catch (error: any) {
        console.error('search__exhibit_tracking V3 Request failed.', error);
    }

    return [];
}
