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

const ae_promises: key_val = {};

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

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

    return ae_promises.load__user_obj;
}

// Updated 2026-01-15
export async function load_ae_obj_li__user({
    api_cfg,
    for_obj_type = 'account',
    for_obj_id = null,
    include_global = true,
    qry_str = null,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 99,
    offset = 0,
    order_by_li = { username: 'ASC' },
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    for_obj_type?: string;
    for_obj_id?: string | null;
    include_global?: boolean;
    qry_str?: 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_User[]> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_li__user() *** for_obj_id=${for_obj_id} include_global=${include_global} qry_str=${qry_str}`
        );
    }

    // SCENARIO A: Text Search
    if (qry_str) {
        const search_query: any = { q: qry_str, and: [] };
        if (for_obj_id && include_global) {
            search_query.and.push({
                or: [
                    { field: `account_id_random`, op: 'eq', value: for_obj_id },
                    { field: `account_id_random`, op: 'eq', value: null }
                ]
            });
        } else if (for_obj_id) {
            search_query.and.push({
                field: `account_id_random`,
                op: 'eq',
                value: for_obj_id
            });
        } else if (include_global) {
            search_query.and.push({
                field: `account_id_random`,
                op: 'eq',
                value: null
            });
        }

        return await api.search_ae_obj({
            api_cfg,
            obj_type: 'user',
            search_query,
            enabled,
            hidden,
            view,
            order_by_li,
            limit,
            offset,
            log_lvl
        });
    }

    // SCENARIO B: Multi-Scope (Account + Global) with no search string
    if (for_obj_id && include_global) {
        if (log_lvl) console.log('Strategy: Multi-call (Account + Global)');
        const [acct_users, global_users] = await Promise.all([
            load_ae_obj_li__user({
                api_cfg,
                for_obj_id,
                include_global: false,
                enabled,
                hidden,
                view,
                limit,
                log_lvl
            }),
            load_ae_obj_li__user({
                api_cfg,
                for_obj_id: null,
                include_global: true,
                enabled,
                hidden,
                view,
                limit,
                log_lvl
            })
        ]);

        // Merge and unique-ify by ID
        const merged = [...acct_users, ...global_users];
        const unique = Array.from(
            new Map(merged.map((u) => [u.user_id_random, u])).values()
        );
        return unique;
    }

    // SCENARIO C: Global Only (no search string)
    if (!for_obj_id && include_global) {
        if (log_lvl) console.log('Strategy: Search API for Global Only');
        // Since for_obj_id is NULL in List API is tricky, use Search with a direct filter
        const search_query = {
            and: [{ field: 'account_id_random', op: 'eq', value: null }]
        };
        return await api.search_ae_obj({
            api_cfg,
            obj_type: 'user',
            search_query,
            enabled,
            hidden,
            view,
            order_by_li,
            limit,
            offset,
            log_lvl
        });
    }

    // SCENARIO D: Account Only or Everything (confirmed working List API)
    if (log_lvl)
        console.log(`Strategy: Standard List API (for_obj_id=${for_obj_id})`);
    return await api.get_ae_obj_li({
        api_cfg,
        obj_type: 'user',
        for_obj_type: for_obj_id ? for_obj_type : undefined,
        for_obj_id: for_obj_id || undefined,
        enabled,
        hidden,
        view,
        limit,
        offset,
        order_by_li,
        log_lvl
    });
}

// Updated 2026-01-06
export async function create_ae_obj__user({
    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_User | null> {
    const fields: key_val = { ...data_kv };
    if (account_id) fields.account_id_random = account_id;

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

    if (result && try_cache) {
        const processed_obj_li = await process_ae_obj__user_props({
            obj_li: [result],
            log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_core,
            table_name: 'user',
            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__user({
    api_cfg,
    user_id,
    data_kv,
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    user_id: string;
    data_kv: key_val;
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_User | null> {
    const result = await api.update_ae_obj({
        api_cfg,
        obj_type: 'user',
        obj_id: user_id,
        fields: data_kv,
        params,
        log_lvl
    });

    if (result && try_cache) {
        const processed_obj_li = await process_ae_obj__user_props({
            obj_li: [result],
            log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_core,
            table_name: 'user',
            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__user({
    api_cfg,
    user_id,
    method = 'delete',
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    user_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: 'user',
        obj_id: user_id,
        method,
        params,
        log_lvl
    });

    if (try_cache) {
        await db_core.user.delete(user_id);
    }

    return result;
}

/*
 * *** V3 AUTHENTICATION FUNCTIONS ***
 *
 * All functions below use the V3 action endpoints:
 *   POST /v3/action/user/authenticate        (was: GET /user/authenticate)
 *   GET  /v3/action/user/{id}/email_auth_key_url  (was: GET /user/{id}/email_auth_key_url)
 *   POST /v3/crud/user/search               (was: GET /user/lookup_email)
 *   POST /v3/action/user/{id}/change_password    (was: PATCH /user/{id}/change_password)
 *
 * Key differences from the legacy routes:
 * - Credentials are in the POST body, not query params (safer — not logged in URLs)
 * - x-account-id header still required to scope username/email lookups to the account
 * - x-no-account-id must still be removed when we have a real account context
 */

// Updated 2026-04-25 — migrated from GET /user/authenticate to POST /v3/action/user/authenticate
export async function auth_ae_obj__username_password({
    api_cfg,
    account_id,
    username,
    password,
    log_lvl = 0
}: {
    api_cfg: any;
    account_id: string;
    username: string;
    password: string;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(
            `*** auth_ae_obj__username_password() *** account_id=${account_id} username=${username}`
        );
    }

    // WHY: Must set x-account-id explicitly so the backend scopes the username lookup
    // to the correct account. Remove x-no-account-id which is only used during bootstrap.
    const use_api_cfg = { ...api_cfg, headers: { ...api_cfg.headers } };
    use_api_cfg.headers['x-account-id'] = account_id;
    delete use_api_cfg.headers['x-no-account-id'];

    ae_promises.auth__username_password = await api
        .post_object({
            api_cfg: use_api_cfg,
            endpoint: '/v3/action/user/authenticate',
            data: { username, password },
            log_lvl
        })
        .then(function (result: any) {
            return result ?? null;
        })
        .catch(function (error: any) {
            console.log('auth_ae_obj__username_password failed:', error);
            return null;
        });

    return ae_promises.auth__username_password;
}

// Updated 2026-04-25 — migrated from GET /user/authenticate to POST /v3/action/user/authenticate
export async function auth_ae_obj__user_id_user_auth_key({
    api_cfg,
    account_id,
    user_id,
    user_auth_key,
    log_lvl = 0
}: {
    api_cfg: any;
    account_id: string;
    user_id: string;
    user_auth_key: string;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(
            `*** auth_ae_obj__user_id_user_auth_key() *** account_id=${account_id} user_id=${user_id}`
        );
    }

    const use_api_cfg = { ...api_cfg, headers: { ...api_cfg.headers } };
    use_api_cfg.headers['x-account-id'] = account_id;
    delete use_api_cfg.headers['x-no-account-id'];

    ae_promises.auth__user_id_user_key = await api
        .post_object({
            api_cfg: use_api_cfg,
            endpoint: '/v3/action/user/authenticate',
            // WHY: valid_email=true marks the user's email as verified on successful magic-link auth
            data: { user_id, auth_key: user_auth_key, valid_email: true },
            log_lvl
        })
        .then(function (result: any) {
            return result ?? null;
        })
        .catch(function (error: any) {
            console.log('auth_ae_obj__user_id_user_auth_key failed:', error);
            return null;
        });

    return ae_promises.auth__user_id_user_key;
}

// Updated 2026-04-25 — migrated from GET /user/{id}/email_auth_key_url to V3 action path
export async function send_email_auth_ae_obj__user_id({
    api_cfg,
    account_id,
    user_id,
    base_url,
    key_param_name = 'user_key',
    log_lvl = 0
}: {
    api_cfg: any;
    account_id: string;
    user_id: string;
    base_url?: string;
    key_param_name?: string;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(
            `*** send_email_auth_ae_obj__user_id() *** account_id=${account_id} user_id=${user_id}`
        );
    }

    const use_api_cfg = { ...api_cfg, headers: { ...api_cfg.headers } };
    use_api_cfg.headers['x-account-id'] = account_id;
    delete use_api_cfg.headers['x-no-account-id'];

    ae_promises.auth_key__send_email = await api.get_object({
        api_cfg: use_api_cfg,
        endpoint: `/v3/action/user/${user_id}/email_auth_key_url`,
        params: { root_url: base_url, key_param_name },
        log_lvl
    });

    return ae_promises.auth_key__send_email;
}

// Updated 2026-04-25 — migrated from GET /user/lookup_email to POST /v3/crud/user/search
export async function qry_ae_obj_li__user_email({
    api_cfg,
    account_id,
    email,
    log_lvl = 0
}: {
    api_cfg: any;
    account_id: string;
    email: string;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(
            `*** qry_ae_obj_li__user_email() *** account_id=${account_id} email=${email}`
        );
    }

    const use_api_cfg = { ...api_cfg, headers: { ...api_cfg.headers } };
    use_api_cfg.headers['x-account-id'] = account_id;
    delete use_api_cfg.headers['x-no-account-id'];

    const results = await api
        .search_ae_obj({
            api_cfg: use_api_cfg,
            obj_type: 'user',
            search_query: { and: [{ field: 'email', op: 'eq', value: email }] },
            log_lvl
        })
        .catch(function (error: any) {
            console.log('qry_ae_obj_li__user_email failed:', error);
            return null;
        });

    // Return the first match to preserve the same interface callers expect
    // (the old /user/lookup_email endpoint returned a single user object)
    return results?.[0] ?? null;
}

// Updated 2026-04-25 — migrated from PATCH /user/{id}/change_password to POST /v3/action
export async function auth_ae_obj__user_id_change_password({
    api_cfg,
    account_id,
    user_id,
    password,
    log_lvl = 0
}: {
    api_cfg: any;
    account_id: string;
    user_id: string;
    password: string;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(
            `*** auth_ae_obj__user_id_change_password() *** account_id=${account_id} user_id=${user_id}`
        );
    }

    ae_promises.change_password__user_id = await api
        .post_object({
            api_cfg,
            endpoint: `/v3/action/user/${user_id}/change_password`,
            data: { new_password: password },
            log_lvl
        })
        .then(function (result: any) {
            return result ?? null;
        })
        .catch(function (error: any) {
            console.log('auth_ae_obj__user_id_change_password failed:', error);
            return null;
        });

    return ae_promises.change_password__user_id;
}

const properties_to_save = [
    'id',
    'user_id',
    'user_id_random',
    'username',
    'name',
    'email',
    'allow_auth_key',
    'super',
    'manager',
    'administrator',
    'verified',
    'public',
    'person_id',
    'person_id_random',
    'enable',
    'enable_from',
    'enable_to',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    'tmp_sort_1',
    'tmp_sort_2'
];

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