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_EventLocation } from '$lib/types/ae_types';
import { load_ae_obj_li__event_file } from '$lib/ae_events/ae_events__event_file';
import { load_ae_obj_li__event_session } from '$lib/ae_events/ae_events__event_session';
import { load_ae_obj_li__event_device } from '$lib/ae_events/ae_events__event_device';

const ae_promises: key_val = {};

// Updated 2026-01-30: Optimized Non-Blocking SWR Pattern
export async function load_ae_obj_id__event_location({
    api_cfg,
    event_location_id,
    view = 'default',
    inc_file_li = false,
    inc_session_li = false,
    inc_presentation_li = false,
    inc_presenter_li = false,
    inc_device_li = false,
    inc_all_file_li = false,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_location_id: string;
    view?: string;
    inc_file_li?: boolean;
    inc_session_li?: boolean;
    inc_presentation_li?: boolean;
    inc_presenter_li?: boolean;
    inc_device_li?: boolean;
    inc_all_file_li?: boolean;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventLocation | null> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_id__event_location() *** [V3] id=${event_location_id} (SWR)`
        );
    }

    // 1. FAST PATH: Cache hit
    if (try_cache) {
        try {
            const cached = await db_events.location.get(event_location_id);
            if (cached) {
                _refresh_location_id_background({
                    api_cfg,
                    event_location_id,
                    view,
                    try_cache,
                    inc_file_li,
                    inc_session_li,
                    inc_presentation_li,
                    inc_presenter_li,
                    inc_device_li,
                    inc_all_file_li,
                    log_lvl: 0
                });
                return await _handle_nested_loads(cached, {
                    api_cfg,
                    inc_file_li,
                    inc_session_li,
                    inc_presentation_li,
                    inc_presenter_li,
                    inc_device_li,
                    inc_all_file_li,
                    log_lvl
                });
            }
        } catch (e) {}
    }

    // 2. SLOW PATH: Wait for API
    return await _refresh_location_id_background({
        api_cfg,
        event_location_id,
        view,
        try_cache,
        inc_file_li,
        inc_session_li,
        inc_presentation_li,
        inc_presenter_li,
        inc_device_li,
        inc_all_file_li,
        log_lvl
    });
}

async function _refresh_location_id_background({
    api_cfg,
    event_location_id,
    view,
    try_cache,
    inc_file_li,
    inc_session_li,
    inc_presentation_li,
    inc_presenter_li,
    inc_device_li,
    inc_all_file_li,
    log_lvl
}: any) {
    if (typeof navigator !== 'undefined' && !navigator.onLine) return null;
    try {
        const result = await api.get_ae_obj({
            api_cfg,
            obj_type: 'event_location',
            obj_id: event_location_id,
            view,
            log_lvl
        });
        if (result) {
            const processed = await process_ae_obj__event_location_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: 'location',
                    obj_li: [processed_obj],
                    properties_to_save,
                    log_lvl
                });
            }
            return await _handle_nested_loads(processed_obj, {
                api_cfg,
                inc_file_li,
                inc_session_li,
                inc_presentation_li,
                inc_presenter_li,
                inc_device_li,
                inc_all_file_li,
                log_lvl
            });
        }
    } catch (e) {}
    return null;
}

// Updated 2026-01-30: Robust Cache Lookups
export async function load_ae_obj_li__event_location({
    api_cfg,
    for_obj_type = 'event',
    for_obj_id,
    inc_file_li = false,
    inc_session_li = false,
    inc_presentation_li = false,
    inc_presenter_li = false,
    inc_device_li = false,
    inc_all_file_li = false,
    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;
    for_obj_type?: string;
    for_obj_id: string;
    inc_file_li?: boolean;
    inc_session_li?: boolean;
    inc_presentation_li?: boolean;
    inc_presenter_li?: boolean;
    inc_device_li?: boolean;
    inc_all_file_li?: boolean;
    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_EventLocation[]> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_li__event_location() *** [V3] for=${for_obj_type}:${for_obj_id} (SWR)`
        );
    }

    // 1. FAST PATH: Check cache
    if (try_cache) {
        try {
            const cached_li = await db_events.location
                .where('event_id')
                .equals(for_obj_id)
                .toArray();
            if (cached_li && cached_li.length > 0) {
                _refresh_location_li_background({
                    api_cfg,
                    for_obj_type,
                    for_obj_id,
                    inc_file_li,
                    inc_session_li,
                    inc_presentation_li,
                    inc_presenter_li,
                    inc_device_li,
                    inc_all_file_li,
                    enabled,
                    hidden,
                    view,
                    limit,
                    offset,
                    order_by_li,
                    try_cache,
                    log_lvl: 0
                });
                for (const loc of cached_li) {
                    _handle_nested_loads(loc, {
                        api_cfg,
                        inc_file_li,
                        inc_session_li,
                        inc_presentation_li,
                        inc_presenter_li,
                        inc_device_li,
                        inc_all_file_li,
                        log_lvl: 0
                    });
                }
                return cached_li;
            }
        } catch (e) {}
    }

    // 2. SLOW PATH: API
    return await _refresh_location_li_background({
        api_cfg,
        for_obj_type,
        for_obj_id,
        inc_file_li,
        inc_session_li,
        inc_presentation_li,
        inc_presenter_li,
        inc_device_li,
        inc_all_file_li,
        enabled,
        hidden,
        view,
        limit,
        offset,
        order_by_li,
        try_cache,
        log_lvl
    });
}

async function _refresh_location_li_background({
    api_cfg,
    for_obj_type,
    for_obj_id,
    inc_file_li,
    inc_session_li,
    inc_presentation_li,
    inc_presenter_li,
    inc_device_li,
    inc_all_file_li,
    enabled,
    hidden,
    view,
    limit,
    offset,
    order_by_li,
    try_cache,
    log_lvl
}: any) {
    if (typeof navigator !== 'undefined' && !navigator.onLine) return [];
    try {
        const result_li = await api.get_ae_obj_li({
            api_cfg,
            obj_type: 'event_location',
            for_obj_type,
            for_obj_id,
            enabled,
            hidden,
            view,
            limit,
            offset,
            order_by_li,
            log_lvl
        });
        if (result_li) {
            const processed = await process_ae_obj__event_location_props({
                obj_li: result_li,
                log_lvl
            });

            // String-Only ID Vision: Ensure linking ID is set for indexing
            if (for_obj_type === 'event') {
                processed.forEach((loc) => (loc.event_id = for_obj_id));
            }

            if (try_cache) {
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_events,
                    table_name: 'location',
                    obj_li: processed,
                    properties_to_save,
                    log_lvl
                });
            }
            for (const loc of processed) {
                _handle_nested_loads(loc, {
                    api_cfg,
                    inc_file_li,
                    inc_session_li,
                    inc_presentation_li,
                    inc_presenter_li,
                    inc_device_li,
                    inc_all_file_li,
                    log_lvl: 0
                });
            }
            return processed;
        }
    } catch (e) {}
    return [];
}

/**
 * Handle nested data loads for a single location object.
 */
async function _handle_nested_loads(
    location_obj: any,
    {
        api_cfg,
        inc_file_li,
        inc_session_li,
        inc_presentation_li,
        inc_presenter_li,
        inc_device_li,
        inc_all_file_li,
        log_lvl
    }: any
) {
    const current_location_id =
        location_obj.id || location_obj.event_location_id;
    if (!current_location_id) return location_obj;

    const tasks = [];
    if (inc_file_li) {
        tasks.push(
            load_ae_obj_li__event_file({
                api_cfg,
                for_obj_type: 'event_location',
                for_obj_id: current_location_id,
                enabled: 'all',
                hidden: 'all',
                log_lvl
            }).then((res) => (location_obj.event_file_li = res))
        );
    }

    if (inc_session_li) {
        tasks.push(
            load_ae_obj_li__event_session({
                api_cfg,
                for_obj_type: 'event_location',
                for_obj_id: current_location_id,
                inc_file_li: inc_all_file_li,
                inc_all_file_li: inc_all_file_li,
                inc_presentation_li: inc_presentation_li,
                inc_presenter_li: inc_presenter_li,
                enabled: 'enabled',
                hidden: 'not_hidden',
                limit: 150,
                log_lvl
            }).then((res) => (location_obj.event_session_obj_li = res))
        );
    }

    if (inc_device_li) {
        tasks.push(
            load_ae_obj_li__event_device({
                api_cfg,
                for_obj_type: 'event_location',
                for_obj_id: current_location_id,
                enabled: 'all',
                limit: 50,
                log_lvl
            }).then((res) => (location_obj.event_device_li = res))
        );
    }

    if (tasks.length > 0) await Promise.all(tasks);
    return location_obj;
}

// Updated 2026-01-20 to V3
export async function create_ae_obj__event_location({
    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_EventLocation | null> {
    const result = await api.create_nested_obj({
        api_cfg,
        for_obj_type: 'event',
        for_obj_id: event_id,
        obj_type: 'event_location',
        fields: { ...data_kv },
        log_lvl
    });

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

// Updated 2026-01-20 to V3
export async function delete_ae_obj_id__event_location({
    api_cfg,
    event_id,
    event_location_id,
    method = 'delete',
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id: string;
    event_location_id: string;
    method?: 'delete' | 'soft_delete' | 'disable' | 'hide';
    try_cache?: boolean;
    log_lvl?: number;
}) {
    const result = await api.delete_nested_ae_obj({
        api_cfg,
        for_obj_type: 'event',
        for_obj_id: event_id,
        obj_type: 'event_location',
        obj_id: event_location_id,
        method,
        log_lvl
    });
    if (try_cache) await db_events.location.delete(event_location_id);
    return result;
}

// Updated 2026-01-20 to V3
export async function update_ae_obj__event_location({
    api_cfg,
    event_id,
    event_location_id,
    data_kv,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id: string;
    event_location_id: string;
    data_kv: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventLocation | null> {
    const result = await api.update_nested_obj({
        api_cfg,
        for_obj_type: 'event',
        for_obj_id: event_id,
        obj_type: 'event_location',
        obj_id: event_location_id,
        fields: data_kv,
        log_lvl
    });
    if (result) {
        const processed = await process_ae_obj__event_location_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: 'location',
                obj_li: [processed_obj],
                properties_to_save,
                log_lvl
            });
        }
        return processed_obj;
    }
    return null;
}

// Updated 2026-01-20 to V3
export async function search__event_location({
    api_cfg,
    event_id,
    qry_str = '',
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 25,
    offset = 0,
    order_by_li = [{ sort: 'ASC' }, { name: 'ASC' }],
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id: string;
    qry_str?: 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_EventLocation[]> {
    const search_query: any = {
        q: qry_str,
        and: [{ field: 'event_id', op: 'eq', value: event_id }]
    };
    if (enabled === 'enabled')
        search_query.and.push({ field: 'enable', op: 'eq', value: true });
    else if (enabled === 'not_enabled')
        search_query.and.push({ field: 'enable', op: 'eq', value: false });
    if (hidden === 'hidden')
        search_query.and.push({ field: 'hide', op: 'eq', value: true });
    else if (hidden === 'not_hidden')
        search_query.and.push({ field: 'hide', op: 'eq', value: false });

    const result_li = await api.search_ae_obj({
        api_cfg,
        obj_type: 'event_location',
        search_query,
        order_by_li,
        view,
        limit,
        offset,
        log_lvl
    });
    if (result_li) {
        const processed = await process_ae_obj__event_location_props({
            obj_li: result_li,
            log_lvl
        });
        if (try_cache) {
            await db_save_ae_obj_li__ae_obj({
                db_instance: db_events,
                table_name: 'location',
                obj_li: processed,
                properties_to_save,
                log_lvl
            });
        }
        return processed;
    }
    return [];
}

export const properties_to_save = [
    'id',
    'event_location_id',
    'event_location_id_random',
    'event_id',
    'event_id_random',
    'external_id',
    'code',
    'name',
    'description',
    'passcode',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    'tmp_sort_1',
    'tmp_sort_2',
    'event_name'
];

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 };
        for (const key in processed_obj) {
            if (key.endsWith('_random')) {
                const newKey = key.slice(0, -7);
                (processed_obj as any)[newKey] = processed_obj[key];
            }
        }
        const randomIdKey = `${obj_type}_id_random`;
        const baseIdKey = `${obj_type}_id`;
        if (processed_obj[randomIdKey])
            (processed_obj as any).id = processed_obj[randomIdKey];
        else if (processed_obj[baseIdKey])
            (processed_obj as any).id = processed_obj[baseIdKey];
        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 ?? '';
        (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__event_location_props({
    obj_li,
    log_lvl = 0
}: {
    obj_li: any[];
    log_lvl?: number;
}) {
    return _process_generic_props({
        obj_li,
        obj_type: 'event_location',
        log_lvl,
        specific_processor: (obj) => {
            if (obj.event_id_random) obj.event_id = obj.event_id_random;
            return obj;
        }
    });
}
