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';

const ae_promises: key_val = {};

// --- PROPERTIES TO SAVE ---
export const properties_to_save = [
    'id',
    'event_badge_template_id',
    'event_id',
    'name',
    'description',
    'logo_filename',
    'logo_path',
    'header_path',
    'background_image_path',
    'secondary_header_path',
    'footer_path',
    'header_row_1',
    'header_row_2',
    'badge_type_list',
    'ticket_list',
    'ticket_1_text',
    'ticket_2_text',
    'ticket_3_text',
    'ticket_4_text',
    'ticket_5_text',
    'ticket_6_text',
    'ticket_7_text',
    'ticket_8_text',
    'wireless_ssid',
    'wireless_password',
    'show_qr_front',
    'show_qr_back',
    'layout',
    'style_filename',
    'style_href',
    'cfg_json',
    'other_json',
    'duplex',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    'tmp_sort_1',
    'tmp_sort_2'
];

/**
 * NON-EXPORTED LOCAL HELPER
 */
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`;
        if (processed_obj[randomIdKey]) {
            (processed_obj as any).id = processed_obj[randomIdKey];
        }

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

// Updated 2026-01-20 to V3
export async function load_ae_obj_id__event_badge_template({
    api_cfg,
    event_badge_template_id,
    view = 'default',
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_badge_template_id: string;
    view?: string;
    try_cache?: boolean;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_id__event_badge_template() *** [V3] id=${event_badge_template_id}`
        );
    }

    try {
        ae_promises.load__event_badge_template_obj = await api.get_ae_obj({
            api_cfg,
            obj_type: 'event_badge_template',
            obj_id: event_badge_template_id,
            view,
            log_lvl
        });

        if (ae_promises.load__event_badge_template_obj) {
            if (try_cache) {
                const processed_obj_li = await process_ae_badge_template_props({
                    obj_li: [ae_promises.load__event_badge_template_obj],
                    log_lvl
                });
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_events,
                    table_name: 'badge_template',
                    obj_li: processed_obj_li,
                    properties_to_save,
                    log_lvl
                });
            }
        } else if (try_cache) {
            ae_promises.load__event_badge_template_obj =
                await db_events.badge_template.get(event_badge_template_id);
        }
    } catch (error: any) {
        if (try_cache) {
            ae_promises.load__event_badge_template_obj =
                await db_events.badge_template.get(event_badge_template_id);
        }
    }

    return ae_promises.load__event_badge_template_obj || null;
}

// Updated 2026-01-20 to V3
export async function load_ae_obj_li__event_badge_template({
    api_cfg,
    event_id,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 50,
    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;
}) {
    try {
        ae_promises.load__event_badge_template_obj_li = await api.get_ae_obj_li(
            {
                api_cfg,
                obj_type: 'event_badge_template',
                for_obj_type: 'event',
                for_obj_id: event_id,
                enabled,
                hidden,
                view,
                limit,
                offset,
                order_by_li,
                log_lvl
            }
        );

        if (ae_promises.load__event_badge_template_obj_li) {
            if (try_cache) {
                const processed_obj_li = await process_ae_badge_template_props({
                    obj_li: ae_promises.load__event_badge_template_obj_li,
                    log_lvl
                });
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_events,
                    table_name: 'badge_template',
                    obj_li: processed_obj_li,
                    properties_to_save,
                    log_lvl
                });
            }
        } else if (try_cache) {
            ae_promises.load__event_badge_template_obj_li =
                await db_events.badge_template
                    .where('event_id')
                    .equals(event_id)
                    .toArray();
        }
    } catch (error: any) {
        if (try_cache) {
            ae_promises.load__event_badge_template_obj_li =
                await db_events.badge_template
                    .where('event_id')
                    .equals(event_id)
                    .toArray();
        }
    }

    return ae_promises.load__event_badge_template_obj_li || [];
}

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

    if (result && try_cache) {
        const processed_obj_li = await process_ae_badge_template_props({
            obj_li: [result],
            log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_events,
            table_name: 'badge_template',
            obj_li: processed_obj_li,
            properties_to_save,
            log_lvl
        });
    }
    return result;
}

// Updated 2026-01-20 to V3
export async function delete_ae_obj_id__event_badge_template({
    api_cfg,
    event_id,
    event_badge_template_id,
    method = 'delete',
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id: string;
    event_badge_template_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_badge_template',
        obj_id: event_badge_template_id,
        method,
        log_lvl
    });

    if (try_cache) {
        await db_events.badge_template.delete(event_badge_template_id);
    }
    return result;
}

// Updated 2026-01-20 to V3
export async function update_ae_obj__event_badge_template({
    api_cfg,
    event_id,
    event_badge_template_id,
    data_kv,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    event_id: string;
    event_badge_template_id: string;
    data_kv: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}) {
    const result = await api.update_nested_obj({
        api_cfg,
        for_obj_type: 'event',
        for_obj_id: event_id,
        obj_type: 'event_badge_template',
        obj_id: event_badge_template_id,
        fields: data_kv,
        log_lvl
    });

    if (result && try_cache) {
        const processed_obj_li = await process_ae_badge_template_props({
            obj_li: [result],
            log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_events,
            table_name: 'badge_template',
            obj_li: processed_obj_li,
            properties_to_save,
            log_lvl
        });
    }
    return result;
}

// Updated 2026-01-20 to V3
export async function search__event_badge_template({
    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;
}) {
    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_badge_template',
        search_query,
        order_by_li,
        limit,
        offset,
        log_lvl
    });

    if (result_li && try_cache) {
        const processed_obj_li = await process_ae_badge_template_props({
            obj_li: result_li,
            log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_events,
            table_name: 'badge_template',
            obj_li: processed_obj_li,
            properties_to_save,
            log_lvl
        });
    }
    return result_li || [];
}
