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_core } from '$lib/ae_core/db_core';

import type { ae_Contact } from '$lib/types/ae_types';

const ae_promises: key_val = {};

// Updated 2026-01-06
export async function load_ae_obj_id__contact({
    api_cfg,
    contact_id,
    view = 'default',
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    contact_id: string;
    view?: string;
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Contact | null> {
    ae_promises.load__contact_obj = await api
        .get_ae_obj({
            api_cfg,
            obj_type: 'contact',
            obj_id: contact_id,
            view,
            params,
            log_lvl
        })
        .then(async (result) => {
            if (result) {
                if (try_cache) {
                    const processed = await process_ae_obj__contact_props({
                        obj_li: [result],
                        log_lvl
                    });
                    await db_save_ae_obj_li__ae_obj({
                        db_instance: db_core,
                        table_name: 'contact',
                        obj_li: processed,
                        properties_to_save,
                        log_lvl
                    });
                }
                return result;
            }
            return null;
        });
    return ae_promises.load__contact_obj;
}

// Updated 2026-01-06
export async function load_ae_obj_li__contact({
    api_cfg,
    for_obj_type = 'account',
    for_obj_id,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 99,
    offset = 0,
    order_by_li = { name: 'ASC' },
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    for_obj_type?: string;
    for_obj_id: string;
    enabled?: 'all' | 'enabled' | 'not_enabled';
    hidden?: 'all' | 'hidden' | 'not_hidden';
    view?: string;
    limit?: number;
    offset?: number;
    order_by_li?: Record<string, 'ASC' | 'DESC'>;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Contact[]> {
    ae_promises.load__contact_obj_li = await api
        .get_ae_obj_li({
            api_cfg,
            obj_type: 'contact',
            for_obj_type,
            for_obj_id,
            enabled,
            hidden,
            view,
            limit,
            offset,
            order_by_li,
            log_lvl
        })
        .then(async (result) => {
            if (result && Array.isArray(result)) {
                if (try_cache) {
                    const processed = await process_ae_obj__contact_props({
                        obj_li: result,
                        log_lvl
                    });
                    await db_save_ae_obj_li__ae_obj({
                        db_instance: db_core,
                        table_name: 'contact',
                        obj_li: processed,
                        properties_to_save,
                        log_lvl
                    });
                }
                return result;
            }
            return [];
        });
    return ae_promises.load__contact_obj_li;
}

// Updated 2026-01-06
export async function create_ae_obj__contact({
    api_cfg,
    account_id,
    data_kv,
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    account_id: string;
    data_kv: key_val;
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Contact | null> {
    const result = await api.create_ae_obj({
        api_cfg,
        obj_type: 'contact',
        fields: {
            account_id_random: account_id,
            ...data_kv
        },
        params,
        log_lvl
    });

    if (result && try_cache) {
        const processed = await process_ae_obj__contact_props({
            obj_li: [result],
            log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_core,
            table_name: 'contact',
            obj_li: processed,
            properties_to_save,
            log_lvl
        });
    }
    return result;
}

// Updated 2026-01-06
export async function update_ae_obj__contact({
    api_cfg,
    contact_id,
    data_kv,
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    contact_id: string;
    data_kv: key_val;
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Contact | null> {
    const result = await api.update_ae_obj({
        api_cfg,
        obj_type: 'contact',
        obj_id: contact_id,
        fields: data_kv,
        params,
        log_lvl
    });

    if (result && try_cache) {
        const processed = await process_ae_obj__contact_props({
            obj_li: [result],
            log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_core,
            table_name: 'contact',
            obj_li: processed,
            properties_to_save,
            log_lvl
        });
    }
    return result;
}

// Updated 2026-01-06
export async function delete_ae_obj_id__contact({
    api_cfg,
    contact_id,
    method = 'delete',
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    contact_id: string;
    method?: 'delete' | 'soft_delete' | 'disable' | 'hide';
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}) {
    const result = await api.delete_ae_obj({
        api_cfg,
        obj_type: 'contact',
        obj_id: contact_id,
        method,
        params,
        log_lvl
    });

    if (try_cache) {
        await db_core.contact.delete(contact_id);
    }
    return result;
}

export const properties_to_save = [
    'id',
    'contact_id',
    'contact_id_random',
    'account_id',
    'account_id_random',
    'for_type',
    'for_id',
    'for_id_random',
    'name',
    'email',
    'phone',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on'
];

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

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