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

import { db_save_ae_obj_li__ae_obj } from '$lib/ae_core/core__idb_dexie';
import { db_archives } from '$lib/ae_archives/db_archives';
import type { ae_Archive } from '$lib/types/ae_types';

import { load_ae_obj_li__archive_content } from '$lib/ae_archives/ae_archives__archive_content';

const ae_promises: key_val = {};

// Updated 2026-01-06
export async function load_ae_obj_id__archive({
    api_cfg,
    archive_id,
    inc_content_li = false,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 99,
    offset = 0,
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    archive_id: string;
    inc_content_li?: boolean;
    enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
    hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
    view?: string;
    limit?: number;
    offset?: number;
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Archive | null> {
    if (log_lvl) {
        console.log(`*** load_ae_obj_id__archive() *** archive_id=${archive_id}`);
    }

    ae_promises.load__archive_obj = await api
        .get_ae_obj_v3({
            api_cfg: api_cfg,
            obj_type: 'archive',
            obj_id: archive_id,
            view,
            // Only pass view and specific params to avoid 422 validation errors on single-obj endpoints
            params: params,
            log_lvl: log_lvl
        })
        .then(async function (archive_obj_get_result) {
            if (archive_obj_get_result) {
                if (try_cache) {
                    const processed_obj_li = await process_ae_obj__archive_props({
                        obj_li: [archive_obj_get_result],
                        log_lvl: log_lvl
                    });
                    await db_save_ae_obj_li__ae_obj({
                        db_instance: db_archives,
                        table_name: 'archive',
                        obj_li: processed_obj_li,
                        properties_to_save: properties_to_save,
                        log_lvl: log_lvl
                    });
                }
                return archive_obj_get_result;
            } else {
                console.log('No results returned.');
                return null;
            }
        })
        .catch(function (error: any) {
            console.log('No results returned or failed.', error);
        });

    if (inc_content_li && ae_promises.load__archive_obj) {
        // Load the contents for the archive
        const load_archive_content_obj_li = await load_ae_obj_li__archive_content({
            api_cfg: api_cfg,
            for_obj_type: 'archive',
            for_obj_id: archive_id,
            enabled: enabled,
            hidden: hidden,
            limit: limit,
            offset: offset,
            params: params,
            try_cache: try_cache,
            log_lvl: log_lvl
        });
        ae_promises.load__archive_obj.archive_content_li = load_archive_content_obj_li;
    }

    return ae_promises.load__archive_obj;
}

// Updated 2026-01-06
export async function load_ae_obj_li__archive({
    api_cfg,
    for_obj_type = 'account',
    for_obj_id,
    inc_content_li = false,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 99,
    offset = 0,
    order_by_li = {
        priority: 'DESC',
        sort: 'DESC',
        name: 'ASC',
        updated_on: 'DESC',
        created_on: 'DESC'
    } as const,
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    for_obj_type: string;
    for_obj_id: string;
    inc_content_li?: boolean;
    enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
    hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
    view?: string;
    limit?: number;
    offset?: number;
    order_by_li?: Record<string, 'ASC' | 'DESC'> | Record<string, 'ASC' | 'DESC'>[];
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Archive[]> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_li__archive() *** for_obj_type=${for_obj_type} for_obj_id=${for_obj_id}`
        );
    }
    
    // DEBUG: Trace massive content loads
    if (inc_content_li) {
        console.warn(`load_ae_obj_li__archive: Loading content for ALL archives in list! Limit: ${limit}`);
        // console.trace(); 
    }

    ae_promises.load__archive_obj_li = await api
        .get_ae_obj_li_v3({
            api_cfg,
            obj_type: 'archive',
            for_obj_type,
            for_obj_id,
            enabled,
            hidden,
            view,
            limit,
            offset,
            order_by_li,
            log_lvl
        })
        .then(async function (archive_obj_li_get_result) {
            if (archive_obj_li_get_result) {
                if (try_cache) {
                    const processed_obj_li = await process_ae_obj__archive_props({
                        obj_li: archive_obj_li_get_result,
                        log_lvl: log_lvl
                    });
                    await db_save_ae_obj_li__ae_obj({
                        db_instance: db_archives,
                        table_name: 'archive',
                        obj_li: processed_obj_li,
                        properties_to_save: properties_to_save,
                        log_lvl: log_lvl
                    });
                }
                return archive_obj_li_get_result;
            } else {
                return [];
            }
        });

    const archive_obj_li = await ae_promises.load__archive_obj_li;

    if (inc_content_li && archive_obj_li && Array.isArray(archive_obj_li)) {
        for (let i = 0; i < archive_obj_li.length; i++) {
            const archive_obj = archive_obj_li[i];
            const archive_id = archive_obj.archive_id_random;

            const content_li = await load_ae_obj_li__archive_content({
                api_cfg: api_cfg,
                for_obj_type: 'archive',
                for_obj_id: archive_id,
                enabled,
                hidden,
                limit,
                offset,
                params,
                try_cache,
                log_lvl
            });
            archive_obj_li[i].archive_content_li = content_li;
        }
    }

    return archive_obj_li;
}

// Updated 2026-01-06
export async function create_ae_obj__archive({
    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_Archive | null> {
    if (log_lvl) {
        console.log(`*** create_ae_obj__archive() *** account_id=${account_id}`);
    }

    const result = await api.create_ae_obj_v3({
        api_cfg,
        obj_type: 'archive',
        fields: {
            account_id_random: account_id,
            ...data_kv
        },
        params,
        log_lvl
    });

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

    return result;
}

// Updated 2026-01-06
export async function delete_ae_obj_id__archive({
    api_cfg,
    archive_id,
    method = 'delete',
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    archive_id: string;
    method?: 'delete' | 'soft_delete' | 'disable' | 'hide';
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log(`*** delete_ae_obj_id__archive() *** archive_id=${archive_id}`);
    }

    const result = await api.delete_ae_obj_v3({
        api_cfg,
        obj_type: 'archive',
        obj_id: archive_id,
        method,
        params,
        log_lvl
    });

    if (try_cache) {
        await db_archives.archive.delete(archive_id);
    }

    return result;
}

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

    const result = await api.update_ae_obj_v3({
        api_cfg,
        obj_type: 'archive',
        obj_id: archive_id,
        fields: data_kv,
        params,
        log_lvl
    });

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

    return result;
}

// Updated 2026-01-06
export async function qry__archive({
    api_cfg,
    account_id,
    qry_str,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 50,
    offset = 0,
    order_by_li = {
        priority: 'DESC',
        sort: 'DESC',
        name: 'ASC',
        updated_on: 'DESC',
        created_on: 'DESC'
    },
    log_lvl = 0
}: {
    api_cfg: any;
    account_id: string;
    qry_str?: string;
    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_Archive[]> {
    const search_query: any = { and: [] };

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

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

    ae_promises.load__archive_obj_li = await api.search_ae_obj_v3({
        api_cfg,
        obj_type: 'archive',
        search_query,
        enabled,
        hidden,
        view,
        limit,
        offset,
        order_by_li,
        log_lvl
    });

    return ae_promises.load__archive_obj_li;
}

// Updated 2025-06-04
export const properties_to_save = [
    'id',
    'archive_id',
    'code',
    'account_id',
    'name',
    'description',
    'original_datetime',
    'original_timezone',
    'original_location',
    'original_url',
    'original_url_text',
    'sort_by',
    'sort_by_desc',
    'cfg_json',
    'enable',
    '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.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;
}

// Updated 2025-06-04
export async function process_ae_obj__archive_props({
    obj_li,
    log_lvl = 0
}: {
    obj_li: any[];
    log_lvl?: number;
}) {
    return _process_generic_props({
        obj_li,
        obj_type: 'archive',
        log_lvl,
        specific_processor: (obj) => {
            const sort_val = (obj.sort ?? 0).toString().padStart(3, '0');
            obj.tmp_sort_1 = `${obj.group ?? ''}_${obj.priority ? '1' : '0'}_${
                sort_val
            }_${obj.updated_on ?? obj.created_on}`;
            obj.tmp_sort_2 = `${obj.group ?? ''}_${obj.priority ? '1' : '0'}_${
                sort_val
            }_${obj.updated_on}_${obj.created_on}`;

            return obj;
        }
    });
}