import { get } from 'svelte/store';
import { slct } from '$lib/stores/ae_stores';
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_EventDevice } from '$lib/types/ae_types';

import { load_ae_obj_id__event_location } from './ae_events__event_location';

const ae_promises: key_val = {};

// Updated 2026-01-27 to V3 String-Only ID Standard
export async function load_ae_obj_id__event_device({
    api_cfg,
    event_device_id,
    view = 'default',
    inc_location_id = false,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_device_id: string;
    view?: string;
    inc_location_id?: boolean;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventDevice | null> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_id__event_device() *** [V3] id=${event_device_id}`
        );
    }

    try {
        const result = await api.get_ae_obj({
            api_cfg,
            obj_type: 'event_device',
            obj_id: event_device_id,
            view,
            log_lvl
        });

        if (result) {
            const processed = await process_ae_obj__event_device_props({
                obj_li: [result],
                log_lvl
            });
            ae_promises.load__event_device_obj = processed[0];

            if (try_cache) {
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_events,
                    table_name: 'device',
                    obj_li: [ae_promises.load__event_device_obj],
                    properties_to_save,
                    log_lvl
                });
            }
        } else if (try_cache) {
            ae_promises.load__event_device_obj =
                await db_events.device.get(event_device_id);
        }
    } catch (error: any) {
        console.log('V3 Request failed.', error);
        if (try_cache) {
            ae_promises.load__event_device_obj =
                await db_events.device.get(event_device_id);
        }
    }

    if (!ae_promises.load__event_device_obj) return null;

    if (inc_location_id) {
        const current_location_id =
            ae_promises.load__event_device_obj.event_location_id;
        if (current_location_id) {
            ae_promises.load__event_device_obj.event_location_obj =
                await load_ae_obj_id__event_location({
                    api_cfg,
                    event_location_id: current_location_id,
                    try_cache,
                    log_lvl
                });
        }
    }

    return ae_promises.load__event_device_obj;
}

// Updated 2026-01-27 to V3 String-Only ID Standard
export async function load_ae_obj_li__event_device({
    api_cfg,
    for_obj_type = 'event',
    for_obj_id,
    inc_location_id = false,
    enabled = 'enabled',
    hidden = 'not_hidden',
    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_location_id?: boolean;
    enabled?: 'enabled' | 'all' | 'not_enabled';
    hidden?: 'hidden' | 'all' | 'not_hidden';
    limit?: number;
    offset?: number;
    order_by_li?: any;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventDevice[]> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_li__event_device() *** [V3] for=${for_obj_type}:${for_obj_id}`
        );
    }

    try {
        const result_li = await api.get_ae_obj_li({
            api_cfg,
            obj_type: 'event_device',
            for_obj_type,
            for_obj_id,
            enabled,
            hidden,
            limit,
            offset,
            order_by_li,
            log_lvl
        });

        if (result_li) {
            const processed = await process_ae_obj__event_device_props({
                obj_li: result_li,
                log_lvl
            });
            ae_promises.load__event_device_obj_li = processed;

            if (try_cache) {
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_events,
                    table_name: 'device',
                    obj_li: ae_promises.load__event_device_obj_li,
                    properties_to_save,
                    log_lvl
                });
            }
        } else if (try_cache) {
            ae_promises.load__event_device_obj_li = await db_events.device
                .where('event_id')
                .equals(for_obj_id)
                .toArray();
        }
    } catch (error: any) {
        console.log('V3 List Request failed.', error);
        if (try_cache) {
            ae_promises.load__event_device_obj_li = await db_events.device
                .where('event_id')
                .equals(for_obj_id)
                .toArray();
        }
    }

    if (inc_location_id && ae_promises.load__event_device_obj_li) {
        for (const device of ae_promises.load__event_device_obj_li) {
            if (device.event_location_id) {
                device.event_location_obj =
                    await load_ae_obj_id__event_location({
                        api_cfg,
                        event_location_id: device.event_location_id,
                        try_cache,
                        log_lvl
                    });
            }
        }
    }

    return ae_promises.load__event_device_obj_li || [];
}

// Updated 2026-01-20 to V3
export async function create_ae_obj__event_device({
    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_EventDevice | null> {
    if (!event_id) event_id = get(slct).event_id;
    if (!event_id) {
        console.error('create_ae_obj__event_device: event_id is required');
        return null;
    }
    if (log_lvl) {
        console.log(
            `*** create_ae_obj__event_device() *** [V3] event_id=${event_id}`
        );
    }

    const result = await api.create_nested_obj({
        api_cfg,
        for_obj_type: 'event',
        for_obj_id: event_id,
        obj_type: 'event_device',
        fields: { ...data_kv },
        log_lvl
    });

    if (result) {
        const processed = await process_ae_obj__event_device_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: 'device',
                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_device({
    api_cfg,
    event_id,
    event_device_id,
    method = 'delete',
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id?: string;
    event_device_id: string;
    method?: 'delete' | 'soft_delete' | 'disable' | 'hide';
    try_cache?: boolean;
    log_lvl?: number;
}) {
    if (!event_id) event_id = get(slct).event_id;
    if (!event_id) {
        console.error('delete_ae_obj_id__event_device: event_id is required');
        return null;
    }
    if (log_lvl) {
        console.log(
            `*** delete_ae_obj_id__event_device() *** [V3] id=${event_device_id}`
        );
    }

    const result = await api.delete_nested_ae_obj({
        api_cfg,
        for_obj_type: 'event',
        for_obj_id: event_id,
        obj_type: 'event_device',
        obj_id: event_device_id,
        method,
        log_lvl
    });

    if (try_cache) {
        await db_events.device.delete(event_device_id);
    }

    return result;
}

// Updated 2026-01-20 to V3
export async function update_ae_obj__event_device({
    api_cfg,
    event_id,
    event_device_id,
    data_kv,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id?: string;
    event_device_id: string;
    data_kv: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventDevice | null> {
    if (!event_id) event_id = get(slct).event_id;
    if (!event_id) {
        console.error('update_ae_obj__event_device: event_id is required');
        return null;
    }
    if (log_lvl) {
        console.log(
            `*** update_ae_obj__event_device() *** [V3] id=${event_device_id}`
        );
    }

    const result = await api.update_nested_obj({
        api_cfg,
        for_obj_type: 'event',
        for_obj_id: event_id,
        obj_type: 'event_device',
        obj_id: event_device_id,
        fields: data_kv,
        log_lvl
    });

    if (result) {
        const processed = await process_ae_obj__event_device_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: 'device',
                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_device({
    api_cfg,
    event_id,
    qry_str = '',
    enabled = 'enabled',
    hidden = 'not_hidden',
    limit = 25,
    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;
    qry_str?: string;
    enabled?: 'enabled' | 'all' | 'not_enabled';
    hidden?: 'hidden' | 'all' | 'not_hidden';
    limit?: number;
    offset?: number;
    order_by_li?: any;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_EventDevice[]> {
    if (log_lvl) {
        console.log(
            `*** search__event_device() *** [V3] event_id=${event_id} qry=${qry_str}`
        );
    }

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

    // Logical filters
    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_device',
        search_query,
        order_by_li,
        limit,
        offset,
        log_lvl
    });

    if (result_li) {
        const processed = await process_ae_obj__event_device_props({
            obj_li: result_li,
            log_lvl
        });

        if (try_cache) {
            await db_save_ae_obj_li__ae_obj({
                db_instance: db_events,
                table_name: 'device',
                obj_li: processed,
                properties_to_save,
                log_lvl
            });
        }
        return processed;
    }

    return [];
}

export const properties_to_save = [
    'id',
    'event_device_id',
    'event_id',
    'event_location_id',
    'code',
    'name',
    'description',
    'passcode',
    'local_file_cache_path',
    'host_file_temp_path',
    'recording_path',
    'record_audio',
    'record_video',
    'trigger_open_file_id',
    'trigger_open_session_id',
    'trigger_recording_start',
    'trigger_recording_stop',
    'trigger_reset',
    'trigger_show_admin',
    'trigger_show_hidden',
    'alert',
    'alert_msg',
    'alert_on',
    'status',
    'status_msg',
    'status_on',
    'record_status',
    'record_status_msg',
    'record_status_on',
    'heartbeat',
    'info_hostname',
    'info_ip_list',
    'meta_json',
    'other_json',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    'tmp_sort_1',
    'tmp_sort_2',
    'event_name',
    'event_location_code',
    'event_location_name'
];

/**
 * NON-EXPORTED LOCAL HELPER
 * Processes a list of Aether objects by applying common and specific transformations.
 */
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. Standardize ID and other '_random' fields
        for (const key in processed_obj) {
            if (key.endsWith('_random')) {
                const newKey = key.slice(0, -7);
                (processed_obj as any)[newKey] = processed_obj[key];
            }
        }
        // String-Only ID Vision: Map [obj_type]_id_random to 'id'
        const randomIdKey = `${obj_type}_id_random`;
        if (processed_obj[randomIdKey]) {
            (processed_obj as any).id = processed_obj[randomIdKey];
        }

        // 2. Create common computed properties
        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_device_props({
    obj_li,
    log_lvl = 0
}: {
    obj_li: any[];
    log_lvl?: number;
}) {
    return _process_generic_props({
        obj_li,
        obj_type: 'event_device',
        log_lvl,
        specific_processor: (obj) => {
            // Note: V3 API returns proper ISO strings.
            // We no longer manually append 'Z' to avoid timezone corruption.
            return obj;
        }
    });
}
