import type { key_val } from '$lib/stores/ae_stores';
import { api } from '$lib/ae_api/api';
import { build_tmp_sort } from '$lib/ae_core/core__idb_sort';

import { db_save_ae_obj_li__ae_obj } from '$lib/ae_core/core__idb_dexie';
import { db_posts } from '$lib/ae_posts/db_posts';
import type { ae_Post } from '$lib/types/ae_types';

import { load_ae_obj_li__post_comment } from '$lib/ae_posts/ae_posts__post_comment';

const ae_promises: key_val = {};

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

    ae_promises.load__post_obj = await api
        .get_ae_obj({
            api_cfg: api_cfg,
            obj_type: 'post',
            obj_id: post_id,
            view,
            params,
            log_lvl: log_lvl
        })
        .then(async function (post_obj_get_result) {
            if (post_obj_get_result) {
                if (try_cache) {
                    const processed_obj_li = await process_ae_obj__post_props({
                        obj_li: [post_obj_get_result],
                        log_lvl: log_lvl
                    });
                    await db_save_ae_obj_li__ae_obj({
                        db_instance: db_posts,
                        table_name: 'post',
                        obj_li: processed_obj_li,
                        properties_to_save: properties_to_save,
                        log_lvl: log_lvl
                    });
                }
                return post_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_comment_li && ae_promises.load__post_obj) {
        ae_promises.load__post_obj.post_comment_li =
            await load_ae_obj_li__post_comment({
                api_cfg: api_cfg,
                for_obj_type: 'post',
                for_obj_id: post_id,
                enabled,
                hidden,
                limit,
                offset,
                params,
                try_cache,
                log_lvl
            });
    }

    return ae_promises.load__post_obj;
}

// Updated 2026-01-07
export async function load_ae_obj_li__post({
    api_cfg,
    for_obj_type = 'account',
    for_obj_id,
    inc_comment_li = false,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 99,
    offset = 0,
    order_by_li = {
        priority: 'DESC',
        sort: 'DESC',
        updated_on: 'DESC',
        created_on: 'DESC'
    },
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    for_obj_type: string;
    for_obj_id: string;
    inc_comment_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'>;
    params?: key_val;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Post[]> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_li__post() *** for_obj_type=${for_obj_type} for_obj_id=${for_obj_id}`
        );
    }

    ae_promises.load__post_obj_li = await api
        .get_ae_obj_li({
            api_cfg: api_cfg,
            obj_type: 'post',
            for_obj_type,
            for_obj_id,
            enabled,
            hidden,
            view,
            limit,
            offset,
            order_by_li,
            log_lvl
        })
        .then(async function (post_obj_li_get_result) {
            if (post_obj_li_get_result) {
                if (try_cache) {
                    const processed_obj_li = await process_ae_obj__post_props({
                        obj_li: post_obj_li_get_result,
                        account_id:
                            for_obj_type === 'account' ? for_obj_id : undefined,
                        log_lvl: log_lvl
                    });
                    await db_save_ae_obj_li__ae_obj({
                        db_instance: db_posts,
                        table_name: 'post',
                        obj_li: processed_obj_li,
                        properties_to_save: properties_to_save,
                        log_lvl: log_lvl
                    });
                }
                return post_obj_li_get_result;
            } else {
                return [];
            }
        });

    if (inc_comment_li && ae_promises.load__post_obj_li) {
        for (let i = 0; i < ae_promises.load__post_obj_li.length; i++) {
            const post_obj = ae_promises.load__post_obj_li[i];
            ae_promises.load__post_obj_li[i].post_comment_li =
                await load_ae_obj_li__post_comment({
                    api_cfg: api_cfg,
                    for_obj_type: 'post',
                    for_obj_id: post_obj.post_id,
                    enabled,
                    hidden,
                    limit,
                    offset,
                    params,
                    try_cache,
                    log_lvl
                });
        }
    }

    return ae_promises.load__post_obj_li;
}

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

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

    if (result && try_cache) {
        const processed_obj_li = await process_ae_obj__post_props({
            obj_li: [result],
            account_id,
            log_lvl: log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_posts,
            table_name: 'post',
            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__post({
    api_cfg,
    post_id,
    method = 'delete',
    params = {},
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    post_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__post() *** post_id=${post_id}`);
    }

    const result = await api.delete_ae_obj({
        api_cfg,
        obj_type: 'post',
        obj_id: post_id,
        method,
        params,
        log_lvl
    });

    if (try_cache) {
        await db_posts.post.delete(post_id);
    }

    return result;
}

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

    const result = await api.update_ae_obj({
        api_cfg,
        obj_type: 'post',
        obj_id: post_id,
        fields: data_kv,
        params,
        log_lvl
    });

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

    return result;
}

// Updated 2026-01-07
export async function qry__post({
    api_cfg,
    account_id,
    qry_str,
    qry_person_id = null,
    qry_archive_on = null,
    inc_comment_li = false,
    enabled = 'enabled',
    hidden = 'not_hidden',
    view = 'default',
    limit = 50,
    offset = 0,
    order_by_li = {
        priority: 'DESC',
        sort: 'DESC',
        updated_on: 'DESC',
        created_on: 'DESC'
    },
    log_lvl = 0
}: {
    api_cfg: any;
    account_id: string;
    qry_str?: string;
    qry_person_id?: string | null;
    qry_archive_on?: string | null;
    inc_comment_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'>;
    log_lvl?: number;
}): Promise<ae_Post[]> {
    const search_query: any = { and: [] };

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

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

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

    // if (qry_archive_on) {
    //     // Show posts that are NOT archived yet (archive_on is null OR archive_on > qry_archive_on)
    //     // Note: This logic assumes 'qry_archive_on' is effectively "now" or a cutoff date.
    //     // Complex OR logic inside AND might need specific backend structure support.
    //     // For now, assuming standard AND(OR) structure is supported or we iterate.
    //     // If the backend doesn't support nested ORs easily, we might need multiple queries or rely on client-side filter for this specific edge case
    //     // But let's try to construct it.
    //     //
    //     // V3 search_query structure usually allows top level `or` or `and`.
    //     // To do (A AND (B OR C)), we might need to nest.
    //     // If nesting isn't fully supported, we might just filter for `archive_on > date` and accept that NULLs might be excluded if we aren't careful,
    //     // OR we can just fetch all and filter locally if the volume is low.
    //     //
    //     // Let's try adding a simple filter for now. If the user passes a date, they likely want things visible AFTER that date.
    //     search_query.and.push({ field: 'archive_on', op: 'gt', value: qry_archive_on });

    //     // TODO: Handle 'archive_on IS NULL' case if the backend doesn't treat NULL as "infinite future".
    //     // Often, 'active' posts have archive_on = NULL.
    //     // If we only query 'gt', we lose NULLs.
    //     // Workaround: Don't filter by archive_on in API, filter in processor or client if backend is rigid.
    //     // Or check if backend supports 'is: null'.
    // }

    ae_promises.load__post_obj_li = await api
        .search_ae_obj({
            api_cfg,
            obj_type: 'post',
            search_query,
            enabled,
            hidden,
            view,
            limit,
            offset,
            order_by_li,
            log_lvl
        })
        .then(async function (post_obj_li_get_result) {
            if (post_obj_li_get_result) {
                const processed_obj_li = await process_ae_obj__post_props({
                    obj_li: post_obj_li_get_result,
                    account_id,
                    log_lvl: log_lvl
                });
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_posts,
                    table_name: 'post',
                    obj_li: processed_obj_li,
                    properties_to_save: properties_to_save,
                    log_lvl: log_lvl
                });
                return post_obj_li_get_result;
            } else {
                return [];
            }
        });

    if (inc_comment_li && ae_promises.load__post_obj_li) {
        for (let i = 0; i < ae_promises.load__post_obj_li.length; i++) {
            const post_obj = ae_promises.load__post_obj_li[i];
            ae_promises.load__post_obj_li[i].post_comment_li =
                await load_ae_obj_li__post_comment({
                    api_cfg: api_cfg,
                    for_obj_type: 'post',
                    for_obj_id: post_obj.post_id,
                    enabled,
                    hidden,
                    limit,
                    offset,
                    // params,
                    try_cache: true, // Always cache comments if we are caching posts
                    log_lvl
                });
        }
    }

    return ae_promises.load__post_obj_li;
}

// Updated 2025-06-04
export const properties_to_save = [
    'id',
    'post_id',
    'account_id',
    'external_person_id',
    'topic_id',
    'topic',
    'topic_name',
    'name',
    'title',
    'content',
    'anonymous',
    'full_name',
    'email',
    'notify',
    'enable_comments',
    'archive',
    'archive_on',
    'linked_li_json',
    'cfg_json',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    'tmp_sort_1',
    'tmp_sort_2',
    'post_comment_count'
];

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

// Updated 2026-01-07
export async function process_ae_obj__post_props({
    obj_li,
    account_id,
    log_lvl = 0
}: {
    obj_li: any[];
    account_id?: string;
    log_lvl?: number;
}) {
    return _process_generic_props({
        obj_li,
        obj_type: 'post',
        log_lvl,
        specific_processor: (obj) => {
            if (account_id) {
                if (!obj.account_id) obj.account_id = account_id;
                if (!obj.account_id_random) obj.account_id_random = account_id;
            }
            obj.name = obj.title;
            const { tmp_sort_1, tmp_sort_2 } = build_tmp_sort({
                prefix: [obj.group ?? ''],
                priority: obj.priority,
                sort: obj.sort,
                fields_1: [obj.updated_on ?? obj.created_on ?? ''],
                fields_2: [obj.updated_on ?? '', obj.created_on ?? ''],
                pad_width: 8
            });
            obj.tmp_sort_1 = tmp_sort_1;
            obj.tmp_sort_2 = tmp_sort_2;

            return obj;
        }
    });
}
