import type { key_val } from '$lib/stores/ae_stores';
import { api } from '$lib/ae_api/api';
import type { ae_ActivityLog } from '$lib/types/ae_types';

const ae_promises: key_val = {};

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

    ae_promises.load__activity_log_obj = await api.get_ae_obj({
        api_cfg,
        obj_type: 'activity_log',
        obj_id: activity_log_id,
        view,
        params,
        log_lvl
    });

    return ae_promises.load__activity_log_obj;
}

// Updated 2026-01-06
export async function load_ae_obj_li__activity_log({
    api_cfg,
    for_obj_type = 'account',
    for_obj_id,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 99,
    offset = 0,
    order_by_li = { created_on: 'DESC' },
    params = {},
    log_lvl = 0
}: {
    api_cfg: any;
    for_obj_type?: string;
    for_obj_id: string;
    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;
    log_lvl?: number;
}): Promise<ae_ActivityLog[]> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_li__activity_log() *** for_obj_id=${for_obj_id}`
        );
    }

    ae_promises.load__activity_log_obj_li = await api.get_ae_obj_li({
        api_cfg,
        obj_type: 'activity_log',
        for_obj_type,
        for_obj_id,
        enabled,
        hidden,
        view,
        limit,
        offset,
        order_by_li,
        log_lvl
    });

    return ae_promises.load__activity_log_obj_li;
}

// Updated 2026-01-06
export async function create_ae_obj__activity_log({
    api_cfg,
    account_id,
    data_kv,
    params = {},
    log_lvl = 0
}: {
    api_cfg: any;
    account_id: string;
    data_kv: key_val;
    params?: key_val;
    log_lvl?: number;
}): Promise<ae_ActivityLog | null> {
    if (log_lvl) {
        console.log(
            `*** create_ae_obj__activity_log() *** account_id=${account_id}`
        );
    }

    if (!account_id) {
        console.log(
            `ERROR: Core - Activity Log - account_id required to create`
        );
        return null;
    }

    ae_promises.create__activity_log = await api.create_ae_obj({
        api_cfg,
        obj_type: 'activity_log',
        fields: {
            account_id_random: account_id,
            ...data_kv
        },
        params,
        log_lvl
    });

    return ae_promises.create__activity_log;
}

// Updated 2026-01-06
export async function update_ae_obj__activity_log({
    api_cfg,
    activity_log_id,
    data_kv,
    params = {},
    log_lvl = 0
}: {
    api_cfg: any;
    activity_log_id: string;
    data_kv: key_val;
    params?: key_val;
    log_lvl?: number;
}): Promise<ae_ActivityLog | null> {
    if (log_lvl) {
        console.log(
            `*** update_ae_obj__activity_log() *** activity_log_id=${activity_log_id}`
        );
    }

    ae_promises.update__activity_log_obj = await api.update_ae_obj({
        api_cfg,
        obj_type: 'activity_log',
        obj_id: activity_log_id,
        fields: data_kv,
        params,
        log_lvl
    });

    return ae_promises.update__activity_log_obj;
}

// Updated 2026-01-07

export async function qry__activity_log({
    api_cfg,

    account_id,

    qry_str,

    qry_person_id = null,

    enabled = 'all',

    hidden = 'all',

    view = 'default',

    limit = 50,

    offset = 0,

    order_by_li = { created_on: 'DESC' },

    log_lvl = 0
}: {
    api_cfg: any;

    account_id: string;

    qry_str?: string;

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

    log_lvl?: number;
}): Promise<ae_ActivityLog[]> {
    const search_query: any = {};

    const filters: any[] = [];

    if (account_id) {
        filters.push({
            field: 'account_id_random',
            op: 'eq',
            value: account_id
        });
    }

    if (qry_person_id) {
        filters.push({
            field: 'person_id_random',
            op: 'eq',
            value: qry_person_id
        });
    }

    if (filters.length > 0) {
        search_query.and = filters;
    }

    if (qry_str) {
        search_query.q = qry_str;
    }

    ae_promises.load__activity_log_obj_li = await api.search_ae_obj({
        api_cfg,

        obj_type: 'activity_log',

        search_query,

        enabled,

        hidden,

        view,

        limit,

        offset,

        order_by_li,

        log_lvl
    });

    return ae_promises.load__activity_log_obj_li;
}

// Updated 2026-02-16
export const properties_to_save = [
    'id',
    'activity_log_id',
    'activity_log_id_random',
    'account_id',
    'account_id_random',
    'person_id',
    'person_id_random',
    'user_id',
    'user_id_random',
    'external_client_id',
    'url_root',
    'url_full_path',
    'url_params',
    'source',
    'object_type',
    'object_id',
    'object_id_random',
    'name',
    'action',
    'action_on_type',
    'action_on_id',
    'action_on_id_random',
    'description',
    'details',
    'other_json',
    'meta_json',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    'tmp_sort_1',
    'tmp_sort_2',
    'tmp_sort_3'
];

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 ??
            new Date(0).toISOString();
        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_obj__activity_log_props({
    obj_li,
    log_lvl = 0
}: {
    obj_li: any[];
    log_lvl?: number;
}) {
    return _process_generic_props({
        obj_li,
        obj_type: 'activity_log',
        log_lvl
    });
}
