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

const ae_promises: key_val = {};

// Updated 2026-01-06
export async function load_ae_obj_id__person({
    api_cfg,
    person_id,
    view = 'default',
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    person_id: string;
    view?: string;
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Person | null> {
    if (log_lvl) {
        console.log(`*** load_ae_obj_id__person() *** person_id=${person_id}`);
    }

    ae_promises.load__person_obj = await api
        .get_ae_obj({
            api_cfg,
            obj_type: 'person',
            obj_id: person_id,
            view,
            params,
            log_lvl
        })
        .then(async function (result) {
            if (result) {
                if (try_cache) {
                    const processed_obj_li = await process_ae_obj__person_props(
                        {
                            obj_li: [result],
                            log_lvl
                        }
                    );
                    await db_save_ae_obj_li__ae_obj({
                        db_instance: db_core,
                        table_name: 'person',
                        obj_li: processed_obj_li,
                        properties_to_save: properties_to_save,
                        log_lvl
                    });
                }
                return result;
            } else {
                return null;
            }
        });

    return ae_promises.load__person_obj;
}

// Updated 2026-01-06
export async function load_ae_obj_li__person({
    api_cfg,
    for_obj_type = 'account',
    for_obj_id,
    qry_email = null,
    qry_user_id = null,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 99,
    offset = 0,
    order_by_li = {
        family_name: 'ASC',
        given_name: 'ASC',
        updated_on: 'DESC',
        created_on: 'DESC'
    },
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    for_obj_type?: string;
    for_obj_id?: string;
    qry_email?: string | null;
    qry_user_id?: string | null;
    enabled?: 'enabled' | 'all' | 'not_enabled';
    hidden?: 'hidden' | 'all' | 'not_hidden';
    view?: string;
    limit?: number;
    offset?: number;
    order_by_li?: Record<string, 'ASC' | 'DESC'>;
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Person[]> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_li__person() *** for_obj_id=${for_obj_id}`
        );
    }

    let promise;

    if (qry_user_id || qry_email) {
        const search_query: any = {
            and: []
        };

        if (qry_user_id) {
            search_query.and.push({
                field: 'user_id_random',
                op: 'eq',
                value: qry_user_id
            });
        }

        if (qry_email) {
            search_query.and.push({
                field: 'primary_email',
                op: 'eq',
                value: qry_email
            });
        }

        if (for_obj_id) {
            search_query.and.push({
                field: `${for_obj_type}_id_random`,
                op: 'eq',
                value: for_obj_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 });
        }

        promise = api.search_ae_obj({
            api_cfg,
            obj_type: 'person',
            search_query,
            order_by_li,
            limit,
            offset,
            log_lvl
        });
    } else {
        promise = api.get_ae_obj_li({
            api_cfg,
            obj_type: 'person',
            for_obj_type,
            for_obj_id,
            enabled,
            hidden,
            view,
            limit,
            offset,
            order_by_li,
            log_lvl
        });
    }

    ae_promises.load__person_obj_li = await promise.then(
        async function (result_li) {
            if (result_li) {
                if (try_cache) {
                    const processed_obj_li = await process_ae_obj__person_props(
                        {
                            obj_li: result_li,
                            log_lvl
                        }
                    );
                    await db_save_ae_obj_li__ae_obj({
                        db_instance: db_core,
                        table_name: 'person',
                        obj_li: processed_obj_li,
                        properties_to_save: properties_to_save,
                        log_lvl
                    });
                }
                return result_li;
            } else {
                return [];
            }
        }
    );

    return ae_promises.load__person_obj_li;
}

// Updated 2026-01-06
export async function create_ae_obj__person({
    api_cfg,
    account_id,
    user_id,
    data_kv,
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    account_id?: string;
    user_id?: string;
    data_kv: key_val;
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Person | null> {
    const fields: key_val = { ...data_kv };
    if (account_id) fields.account_id_random = account_id;
    if (user_id) fields.user_id_random = user_id;

    const result = await api.create_ae_obj({
        api_cfg,
        obj_type: 'person',
        fields,
        params,
        log_lvl
    });

    if (result && try_cache) {
        const processed_obj_li = await process_ae_obj__person_props({
            obj_li: [result],
            log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_core,
            table_name: 'person',
            obj_li: processed_obj_li,
            properties_to_save: properties_to_save,
            log_lvl
        });
    }

    return result;
}

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

    if (result && try_cache) {
        const processed_obj_li = await process_ae_obj__person_props({
            obj_li: [result],
            log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_core,
            table_name: 'person',
            obj_li: processed_obj_li,
            properties_to_save: properties_to_save,
            log_lvl
        });
    }

    return result;
}

// Updated 2026-01-06
export async function delete_ae_obj_id__person({
    api_cfg,
    person_id,
    method = 'delete',
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    person_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: 'person',
        obj_id: person_id,
        method,
        params,
        log_lvl
    });

    if (try_cache) {
        await db_core.person.delete(person_id);
    }

    return result;
}

const properties_to_save = [
    'id',
    'person_id',
    'person_id_random',
    'external_id',
    'external_sys_id',
    'code',
    'account_id',
    'account_id_random',
    'person_profile_id',
    'person_profile_id_random',
    'user_id',
    'user_id_random',
    'pronouns',
    'informal_name',
    'title_names',
    'given_name',
    'middle_name',
    'family_name',
    'designations',
    'professional_title',
    'full_name',
    'full_name_override',
    'affiliations',
    'primary_email',
    'biography',
    'agree',
    'comments',
    'allow_auth_key',
    'passcode',
    'data_json',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    'tmp_sort_1',
    'tmp_sort_2',
    'tmp_sort_3',
    'username',
    'user_name',
    'user_email',
    'user_allow_auth_key',
    'user_super',
    'user_manager',
    'user_administrator',
    'user_public',
    'organization_id',
    'organization_id_random',
    'organization_name',
    'contact_id',
    'contact_id_random',
    'contact_name',
    'contact_email',
    'contact_cc_email',
    'contact_phone_mobile',
    'contact_phone_home',
    'contact_phone_office',
    'contact_phone_land',
    'contact_phone_fax',
    'contact_phone_other',
    'address_id',
    'address_id_random',
    'address_city',
    'address_country_alpha_2_code'
];

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];
        }

        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.full_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__person_props({
    obj_li,
    log_lvl = 0
}: {
    obj_li: any[];
    log_lvl?: number;
}) {
    return _process_generic_props({
        obj_li,
        obj_type: 'person',
        log_lvl,
        specific_processor: (obj) => {
            obj.tmp_sort_3 = `${obj.group ?? '0'}_${obj.priority ? 1 : 0}_${obj.sort ?? '0'}_${
                obj.family_name ?? ''
            }_${obj.given_name ?? ''}_${obj.updated_on ?? obj.created_on}`;
            return obj;
        }
    });
}
