// Aether API Library (TS)
// This is intended to be used with the Aether API. The goal is to just import all of the core functions and re-export them as a single module. This is to make it easier to import the functions into other modules.
// This needs to be cleaned up and ideally removed the need for Axios.

import type { key_val } from '$lib/stores/ae_stores';

import { delete_object } from '$lib/ae_api/api_delete_object'; // Exported at the end of this file
import { get_object } from '$lib/ae_api/api_get_object'; // Exported at the end of this file
import { patch_object } from '$lib/ae_api/api_patch_object'; // Exported at the end of this file
import { post_object } from '$lib/ae_api/api_post_object'; // Exported at the end of this file

import { get_ae_obj_id_crud } from '$lib/ae_api/api_get__crud_obj_id';
import { get_ae_obj_li_for_obj_id_crud } from '$lib/ae_api/api_get__crud_obj_li_v1';
import { get_ae_obj_li_for_obj_id_crud_v2 } from '$lib/ae_api/api_get__crud_obj_li_v2';
import { get_ae_lookup_li_v3 } from '$lib/ae_api/api_get__lookup_v3';
import {
    get_ae_obj_v3,
    get_nested_ae_obj_v3,
    get_ae_obj_li_v3,
    get_nested_obj_li_v3
} from '$lib/ae_api/api_get__crud_obj_li_v3';
import { search_ae_obj_v3 } from '$lib/ae_api/api_post__crud_search_v3';
import {
    create_ae_obj_v3,
    create_nested_obj_v3,
    update_ae_obj_v3,
    update_nested_obj_v3,
    delete_ae_obj_v3,
    delete_nested_ae_obj_v3
} from '$lib/ae_api/api_post__crud_obj_v3';

import { get_data_store_v3 } from '$lib/ae_api/api_get__data_store_v3';

/**
 * Get a list of lookup objects (V3 with V2 Fallback)
 * Standardized lookup data like countries, timezones, and subdivisions.
 * Updated 2026-02-20
 */
export const get_ae_obj_li_for_lu = async function get_ae_obj_li_for_lu({
    api_cfg,
    for_lu_type,
    enabled = 'enabled',
    hidden = 'not_hidden',
    order_by_li = null,
    limit = 9999,
    offset = 0,
    headers = {},
    params_json = null,
    params = {},
    only_priority = false,
    log_lvl = 1
}: {
    api_cfg: any;
    for_lu_type: string;
    enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
    hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
    order_by_li?: any;
    limit?: number;
    offset?: number;
    headers?: any;
    params_json?: any;
    params?: key_val;
    only_priority?: boolean;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(`*** get_ae_obj_li_for_lu() *** for_lu_type=${for_lu_type}`);
    }

    // Lookup data is global; bypass account-id scope check
    const merged_headers = {
        'x-no-account-id': 'Nothing to See Here',
        ...headers
    };

    // Use V3 system for primary lookup types
    if (['country', 'country_subdivision', 'time_zone'].includes(for_lu_type)) {
        return await get_ae_lookup_li_v3({
            api_cfg,
            lu_type: for_lu_type,
            include_disabled: enabled === 'all',
            only_priority: only_priority,
            params,
            headers: merged_headers,
            log_lvl
        });
    }

    // Delegate to V2 helper for any other legacy lookup types
    return await get_ae_obj_li_for_obj_id_crud_v2({
        api_cfg,
        obj_type: 'lu',
        for_obj_type: for_lu_type,
        enabled,
        hidden,
        order_by_li,
        limit,
        offset,
        headers: merged_headers,
        params_json,
        params,
        log_lvl
    });
};

// Updated 2023-07-24
export const create_ae_obj_crud = async function create_ae_obj_crud({
    api_cfg,
    obj_type,
    field_name = null,
    field_value = null,
    fields = {},
    key,
    jwt = null,
    headers = {},
    params = {},
    data = {},
    return_obj = false,
    obj_v_name = '',
    return_meta = false,
    log_lvl = 0
}: {
    api_cfg: any;
    obj_type: string;
    field_name?: null | string;
    field_value?: any;
    fields?: key_val;
    key: string;
    jwt?: null | string;
    headers?: key_val;
    params?: key_val;
    data?: key_val;
    return_obj?: boolean;
    obj_v_name?: string;
    return_meta?: boolean;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(`*** create_ae_obj_crud() *** obj_type=${obj_type}`);
    }

    data['super_key'] = key;
    data['jwt'] = jwt;

    // V3 Standard: Unified endpoint for all objects
    const endpoint = `/v3/crud/${obj_type}`;

    if (log_lvl) {
        console.log('Endpoint:', endpoint);
    }

    if (return_obj) {
        params['return_obj'] = true;

        // Pass along the view name to use for returning data.
        if (obj_v_name) {
            params['obj_v_name'] = obj_v_name;
        }
    } else {
        params['return_obj'] = false; // NOTE: This is needed because the current default on the API is to return the object.
    }

    if (field_name) {
        data['data_list'] = {}; // Really an object/dict
        data['data_list'][field_name] = field_value;
        // data['data_list']['testing'] = 'asdf 1234';
    } else if (fields) {
        data['data_list'] = fields; // Really an object/dict
    }

    // NOTE: The data object may contain objects that need to be converted to JSON strings. This is done by adding "_json" to the end of the property name. This is done because the API does not support nested objects. This is a limitation of the API.
    if (data['data_list']) {
        if (log_lvl > 1) {
            console.log('Data List:', data['data_list']);
        }
        for (const [key, value] of Object.entries(data['data_list'])) {
            // console.log(key, value);
            if (key.endsWith('_json')) {
                if (log_lvl) {
                    console.log(`${key}: ${value}`);
                }
                data['data_list'][key] = JSON.stringify(value);
            }
        }
    }

    if (log_lvl) {
        console.log('Data:', data);
    }
    // params['xxxxx run_safety_check xxxxx'] = false;
    params['by_alias'] = false;

    if (log_lvl) {
        console.log('Params:', params);
    }

    const object_obj_post_promise = await post_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        params: params,
        data: data,
        log_lvl: log_lvl
    });

    if (log_lvl > 1) {
        console.log(object_obj_post_promise);
    }

    return object_obj_post_promise;
};

// Updated 2023-06-28
export const update_ae_obj_id_crud = async function update_ae_obj_id_crud({
    api_cfg,
    obj_type,
    obj_id,
    field_name,
    field_value,
    fields = {},
    key,
    jwt = null,
    headers = {},
    params = {},
    data = {},
    return_obj = false,
    obj_v_name = '',
    return_meta = false,
    log_lvl = 0
}: {
    api_cfg: any;
    obj_type: string;
    obj_id: string;
    field_name?: string;
    field_value?: any;
    fields?: key_val;
    key: string;
    jwt?: null | string;
    headers?: key_val;
    params?: key_val;
    data?: null | key_val;
    return_obj?: boolean;
    obj_v_name?: string;
    return_meta?: boolean;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log('*** update_ae_obj_id_crud() ***');
    }

    if (!data) {
        data = {};
    }
    data['super_key'] = key;
    data['jwt'] = jwt;

    // V3 Standard: Unified endpoint for all objects
    const endpoint = `/v3/crud/${obj_type}/${obj_id}`;

    if (log_lvl) {
        console.log('Endpoint:', endpoint);
    }

    if (return_obj) {
        params['return_obj'] = true;

        // Pass along the view name to use for returning data.
        if (obj_v_name) {
            params['obj_v_name'] = obj_v_name;
        }
    } else {
        params['return_obj'] = false; // NOTE: This is needed because the current default on the API is to return the object.
    }

    if (field_name) {
        data['data_list'] = {}; // Really an object/dict
        data['data_list'][field_name] = field_value;
        // data['data_list']['testing'] = 'asdf 1234';
    } else if (fields) {
        data['data_list'] = fields; // Really an object/dict
    }

    // NOTE: The data object may contain objects that need to be converted to JSON strings. This is done by adding "_json" to the end of the property name. This is done because the API does not support nested objects. This is a limitation of the API.
    if (data['data_list']) {
        if (log_lvl > 1) {
            console.log('Data List:', data['data_list']);
        }
        for (const [key, value] of Object.entries(data['data_list'])) {
            // console.log(key, value);
            if (key.endsWith('_json')) {
                if (log_lvl) {
                    console.log(`${key}: ${value}`);
                }
                data['data_list'][key] = JSON.stringify(value);
            }
        }
    }

    if (log_lvl) {
        console.log('Data:', data);
    }
    // params['xxxxx run_safety_check xxxxx'] = false;
    params['by_alias'] = false;

    if (log_lvl) {
        console.log('Params:', params);
    }

    const object_obj_patch_promise = await patch_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        params: params,
        data: data,
        log_lvl: log_lvl
    });

    if (log_lvl > 1) {
        console.log(object_obj_patch_promise);
    }

    return object_obj_patch_promise;
};

// Updated 2023-11-14
export const delete_ae_obj_id_crud = async function delete_ae_obj_id_crud({
    api_cfg,
    obj_type,
    obj_id,
    key,
    jwt = null,
    headers = {},
    params = {},
    data = {},
    method = 'delete', // 'delete', 'disable', 'hide'
    return_meta = false,
    log_lvl = 0
}: {
    api_cfg: any;
    obj_type: string;
    obj_id: string;
    key: string;
    jwt?: null | string;
    headers?: any;
    params?: any;
    data?: any;
    method?: string;
    return_meta?: boolean;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(`*** delete_ae_obj_id_crud() *** obj_type: ${obj_type} obj_id: ${obj_id}`);
    }

    data['super_key'] = key;
    data['jwt'] = jwt;
    // NOTE: The key and or JWT should be in the header of the DELETE, GET, PATCH, POST

    // V3 Standard: Unified endpoint for all objects
    const endpoint = `/v3/crud/${obj_type}/${obj_id}`;

    if (log_lvl) {
        console.log('Endpoint:', endpoint);
    }

    if (method) {
        // NOTE: method options: 'delete', 'disable', 'hide'
        params['method'] = method;
    }

    if (log_lvl) {
        console.log('Params:', params);
    }

    const object_obj_delete_promise = await delete_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        params: params,
        data: data,
        log_lvl: log_lvl
    });

    if (log_lvl > 1) {
        console.log(object_obj_delete_promise);
    }

    return object_obj_delete_promise;
};


/* BEGIN: Hosted File Related */

// Updated 2026-01-07
export const download_hosted_file = async function download_hosted_file({
    api_cfg,
    hosted_file_id,
    return_file = true,
    filename,
    auto_download = false,
    params = {},
    log_lvl = 0
}: {
    api_cfg: any;
    hosted_file_id: string;
    return_file?: boolean;
    filename?: string;
    auto_download?: boolean;
    params?: key_val;
    log_lvl?: number;
}) {
    console.log('*** stores_hosted_api.js: download_hosted_file() ***');

    const task_id = hosted_file_id;

    const endpoint = `/v3/action/hosted_file/${hosted_file_id}/download`;
    if (filename) {
        params['filename'] = filename;
    }
    params['return_file'] = true;

    // Inject JWT into URL parameters if available
    if (api_cfg.jwt) {
        params['jwt'] = api_cfg.jwt;
    } else if (api_cfg.headers?.['authorization']) {
        // Fallback: extract from header if present
        const auth_header = api_cfg.headers['authorization'];
        if (auth_header.startsWith('Bearer ')) {
            params['jwt'] = auth_header.substring(7);
        }
    }

    const hosted_file_download_get_promise = await api.get_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        params: params,
        return_blob: return_file,
        filename: filename,
        auto_download: auto_download,
        task_id: task_id,
        log_lvl: log_lvl
    });
    // console.log(hosted_file_download_get_promise);
    return hosted_file_download_get_promise;
};

// Updated 2023-12-15
export const delete_hosted_file = async function delete_hosted_file({
    api_cfg,
    hosted_file_id,
    link_to_type,
    link_to_id,
    rm_orphan = false,
    params = {},
    data = {},
    log_lvl = 1
}: {
    api_cfg: any;
    hosted_file_id: string;
    link_to_type?: string;
    link_to_id?: string;
    rm_orphan?: boolean;
    params?: key_val;
    data?: key_val;
    log_lvl?: number;
}) {
    console.log('*** stores_hosted_api.js: delete_hosted_file() ***');

    const endpoint = `/v3/action/hosted_file/${hosted_file_id}`;
    if (link_to_type) {
        params['link_to_type'] = link_to_type;
    }
    if (link_to_id) {
        params['link_to_id'] = link_to_id;
    }
    if (rm_orphan) {
        params['rm_orphan'] = rm_orphan;
    }

    const hosted_file_obj_delete_promise = await api.delete_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        params: params,
        data: data,
        log_lvl: log_lvl
    });
    // console.log(hosted_file_obj_delete_promise);
    return hosted_file_obj_delete_promise;
};
/* END: Hosted File Related */

/* BEGIN: Data Store Related */

// Updated 2023-06-29
export const get_data_store_obj_w_code = async function get_data_store_obj_w_code({
    api_cfg,
    data_store_code,
    data_type = 'text',
    headers = {},
    params = {},
    timeout = 25000,
    log_lvl = 0
}: {
    api_cfg: any;
    data_store_code: string;
    data_type?: string;
    headers?: key_val;
    params?: key_val;
    timeout?: number;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log('*** get_data_store_obj_w_code() ***');
    }

    // let get_item_result = window.localStorage.getItem(code);

    const endpoint = `/data_store/code/${data_store_code}`;
    let data_store_obj_get_promise = await api.get_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        headers: headers,
        params: params,
        timeout: timeout,
        log_lvl: log_lvl
    });

    if (data_store_obj_get_promise === false) {
        console.log('Data Store - RUN AGAIN WITH BACKUP');
        const original_api_base_url = api_cfg['base_url'];

        const temp_api = api_cfg;
        temp_api['base_url'] = temp_api['base_url_bak'];

        data_store_obj_get_promise = await api.get_object({
            api_cfg: temp_api,
            endpoint: endpoint,
            headers: headers,
            params: params,
            timeout: timeout,
            log_lvl: log_lvl
        });
        temp_api['base_url'] = original_api_base_url;
    }

    const data_store_obj = data_store_obj_get_promise;

    if (data_type == 'text') {
        // console.log(data_store_obj.text);
        // window.localStorage.setItem(data_store_code, data_store_obj.text);
        // localStorage.setItem(data_store_code, data_store_obj.text);
    } else if (data_type == 'json') {
        // console.log(data_store_obj.json);
        // window.localStorage.setItem(data_store_code, JSON.stringify(data_store_obj.json));
        // localStorage.setItem(data_store_code, JSON.stringify(data_store_obj.json));
    }

    if (log_lvl > 1) {
        console.log('Response Data:', data_store_obj);
    }
    return data_store_obj;
};
/* END: Data Store Related */

/* BEGIN: Utility: Email Related */

// Updated 2023-06-29
export const send_email = async function send_email({
    api_cfg,
    from_email,
    from_name = '',
    to_email,
    to_name = '',
    cc_email = null,
    cc_name = null,
    bcc_email = null,
    bcc_name = null,
    subject,
    body_html,
    body_text = null,
    // headers = {},
    params = {},
    data = {},
    return_obj = false,
    return_meta = false,
    test = false,
    log_lvl = 0
}: {
    api_cfg: any;
    from_email: string;
    from_name?: string;
    to_email: string;
    to_name?: string;
    cc_email?: null | string;
    cc_name?: null | string;
    bcc_email?: null | string;
    bcc_name?: null | string;
    subject: string;
    body_html: string;
    body_text?: null | string;
    // headers?: key_val,
    params?: key_val;
    data?: key_val;
    return_obj?: boolean;
    return_meta?: boolean;
    test?: boolean;
    log_lvl?: number;
}) {
    console.log('*** send_email() ***');

    // Skip email sending entirely when running in a test/Playwright environment.
    // Set window.__ae_test_mode = true via addInitScript to activate this guard.
    if (typeof globalThis !== 'undefined' && (globalThis as any).__ae_test_mode) {
        console.log(`[TEST MODE] send_email() suppressed — would have sent to: ${to_email}, subject: ${subject}`);
        return null;
    }

    const endpoint = `/util/email/send`;

    data['from_email'] = from_email; // Required
    data['from_name'] = from_name;

    data['to_email'] = to_email; // Required
    data['to_name'] = to_name;

    data['cc_email'] = cc_email;
    data['cc_name'] = cc_name;

    data['bcc_email'] = bcc_email;
    data['bcc_name'] = bcc_name;

    data['subject'] = subject;
    if (log_lvl) {
        console.log('Data:', data);
    }

    data['body_html'] = body_html;

    data['body_text'] = body_text;

    if (return_obj) {
        params['return_obj'] = true;
    }

    if (test) {
        params['test'] = true;
    }

    const send_email_post_promise = await api.post_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        params: params,
        data: data,
        return_meta: return_meta,
        log_lvl: log_lvl
    });

    if (log_lvl > 1) {
        console.log('Response Data:', send_email_post_promise);
    }
    if (return_obj) {
        return send_email_post_promise;
    } else {
        return send_email_post_promise.event_abstract_id_random;
    }
};

/* END: Utility: Email Related */

const obj = {
    delete_object: delete_object,
    get_object: get_object,
    patch_object: patch_object,
    post_object: post_object,
    get_ae_obj_id_crud: get_ae_obj_id_crud,
    get_ae_obj_v3: get_ae_obj_v3,
    get_nested_ae_obj_v3: get_nested_ae_obj_v3,
    get_ae_obj_li_for_obj_id_crud: get_ae_obj_li_for_obj_id_crud,
    get_ae_obj_li_for_obj_id_crud_v2: get_ae_obj_li_for_obj_id_crud_v2,
    get_ae_obj_li_v3: get_ae_obj_li_v3,
    get_nested_obj_li_v3: get_nested_obj_li_v3,
    search_ae_obj_v3: search_ae_obj_v3,
    create_ae_obj_v3: create_ae_obj_v3,
    create_nested_obj_v3: create_nested_obj_v3,
    update_ae_obj_v3: update_ae_obj_v3,
    update_nested_obj_v3: update_nested_obj_v3,
    delete_ae_obj_v3: delete_ae_obj_v3,
    delete_nested_ae_obj_v3: delete_nested_ae_obj_v3,
    create_ae_obj_crud: create_ae_obj_crud,
    update_ae_obj_id_crud: update_ae_obj_id_crud,
    delete_ae_obj_id_crud: delete_ae_obj_id_crud,
    download_hosted_file: download_hosted_file,
    delete_hosted_file: delete_hosted_file,
    get_data_store_v3: get_data_store_v3,
    get_data_store_obj_w_code: get_data_store_obj_w_code,
    get_ae_obj_li_for_lu: get_ae_obj_li_for_lu,
    send_email: send_email
};
export const api = obj;
// module.exports = api;