import type { key_val } from '$lib/stores/ae_stores';
import { api } from '$lib/ae_api/api';
import { db_sponsorships } from '$lib/ae_sponsorships/db_sponsorships';
import { db_save_ae_obj_li__ae_obj } from '$lib/ae_core/core__idb_dexie';
import type { ae_Sponsorship, ae_SponsorshipCfg } from '$lib/types/ae_types';

const ae_promises: key_val = {};

// --- PROPERTIES TO SAVE ---
export const properties_to_save_sponsorship_cfg = [
    'id',
    'sponsorship_cfg_id',
    'account_id',
    'for_type',
    'for_id',
    'level_li_json',
    'option_li_json',
    'schedule_li_json',
    'cfg_json',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    // Generated fields for sorting locally only
    'tmp_sort_1',
    'tmp_sort_2'
];

// --- PROCESS FUNCTION ---
export async function process_ae_obj__sponsorship_cfg_props({
    obj_li,
    log_lvl = 0
}: {
    obj_li: any[];
    log_lvl?: number;
}) {
    return _process_generic_props({
        obj_li,
        obj_type: 'sponsorship_cfg',
        log_lvl,
        specific_processor: (obj) => {
            // Sponsorship Cfg-specific computed sort fields
            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;
        }
    });
}

// --- PROPERTIES TO SAVE ---
export const properties_to_save_sponsorship = [
    'id',
    'sponsorship_id',
    'account_id',
    'organization_id',
    'person_id',
    'poc_person_id',
    'poc_json',
    'name',
    'name_override',
    'description',
    'email',
    'website_url',
    'logo_li_json',
    'media_li_json',
    'social_li_json',
    'address_li_json',
    'contact_li_json',
    'guest_li_json',
    'level_num',
    'level_str',
    'amount',
    'questions_li_json',
    'agree',
    'comments',
    'staff_notes',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    // Generated fields for sorting locally only
    'tmp_sort_1',
    'tmp_sort_2'
];

// --- PROCESS FUNCTION ---
export async function process_ae_obj__sponsorship_props({
    obj_li,
    log_lvl = 0
}: {
    obj_li: any[];
    log_lvl?: number;
}) {
    return _process_generic_props({
        obj_li,
        obj_type: 'sponsorship',
        log_lvl,
        specific_processor: (obj) => {
            // Sponsorship-specific computed sort fields
            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;
        }
    });
}

/**
 * NON-EXPORTED LOCAL HELPER
 * Processes a list of Aether objects by applying common and specific transformations.
 */
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 (log_lvl > 0) {
        console.log(
            `*** _process_generic_props: Processing ${obj_li.length} objects of type "${obj_type}" ***`
        );
    }

    if (!obj_li || obj_li.length === 0) {
        if (log_lvl > 0) console.log('No objects to process.');
        return [];
    }

    const processed_obj_li: T[] = [];

    for (const original_obj of obj_li) {
        let processed_obj = { ...original_obj };

        // 1. Standardize ID and other '_random' fields
        for (const key in processed_obj) {
            if (key.endsWith('_random')) {
                const newKey = key.slice(0, -7);
                (processed_obj as any)[newKey] = processed_obj[key];
            }
        }
        // Ensure 'id' is set from '[obj_type]_id_random'
        const randomIdKey = `${obj_type}_id_random`;
        if (processed_obj[randomIdKey]) {
            (processed_obj as any).id = processed_obj[randomIdKey];
        }

        // 2. Create common computed properties
        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 2026-03-11: SWR pattern
export async function load_ae_obj_id__sponsorship_cfg({
    api_cfg,
    sponsorship_cfg_id,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    sponsorship_cfg_id: string;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_SponsorshipCfg | null> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_id__sponsorship_cfg() *** [V3] id=${sponsorship_cfg_id} (SWR)`
        );
    }

    // 1. FAST PATH: Cache hit
    if (try_cache) {
        try {
            const cached = await db_sponsorships.cfg.get(sponsorship_cfg_id);
            if (cached) {
                _refresh_sponsorship_cfg_id_background({
                    api_cfg,
                    sponsorship_cfg_id,
                    try_cache,
                    log_lvl: 0
                });
                return cached as unknown as ae_SponsorshipCfg;
            }
        } catch (e) {}
    }

    // 2. SLOW PATH: Wait for API
    return await _refresh_sponsorship_cfg_id_background({
        api_cfg,
        sponsorship_cfg_id,
        try_cache,
        log_lvl
    });
}

async function _refresh_sponsorship_cfg_id_background({
    api_cfg,
    sponsorship_cfg_id,
    try_cache,
    log_lvl
}: any) {
    if (typeof navigator !== 'undefined' && !navigator.onLine) return null;
    try {
        const result = await api.get_ae_obj({
            api_cfg,
            obj_type: 'sponsorship_cfg',
            obj_id: sponsorship_cfg_id,
            log_lvl
        });
        if (result) {
            if (try_cache) {
                const processed_obj_li =
                    await process_ae_obj__sponsorship_cfg_props({
                        obj_li: [result],
                        log_lvl
                    });
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_sponsorships,
                    table_name: 'cfg',
                    obj_li: processed_obj_li,
                    properties_to_save: properties_to_save_sponsorship_cfg,
                    log_lvl
                });
            }
            return result;
        }
    } catch (e) {}
    return null;
}

// Updated 2026-03-11: SWR pattern
export async function load_ae_obj_id__sponsorship({
    api_cfg,
    sponsorship_id,
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    sponsorship_id: string;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Sponsorship | null> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_id__sponsorship() *** [V3] id=${sponsorship_id} (SWR)`
        );
    }

    // 1. FAST PATH: Cache hit
    if (try_cache) {
        try {
            const cached =
                await db_sponsorships.sponsorship.get(sponsorship_id);
            if (cached) {
                _refresh_sponsorship_id_background({
                    api_cfg,
                    sponsorship_id,
                    try_cache,
                    log_lvl: 0
                });
                return cached as unknown as ae_Sponsorship;
            }
        } catch (e) {}
    }

    // 2. SLOW PATH: Wait for API
    return await _refresh_sponsorship_id_background({
        api_cfg,
        sponsorship_id,
        try_cache,
        log_lvl
    });
}

async function _refresh_sponsorship_id_background({
    api_cfg,
    sponsorship_id,
    try_cache,
    log_lvl
}: any) {
    if (typeof navigator !== 'undefined' && !navigator.onLine) return null;
    try {
        const result = await api.get_ae_obj({
            api_cfg,
            obj_type: 'sponsorship',
            obj_id: sponsorship_id,
            log_lvl
        });
        if (result) {
            if (try_cache) {
                const processed_obj_li =
                    await process_ae_obj__sponsorship_props({
                        obj_li: [result],
                        log_lvl
                    });
                await db_save_ae_obj_li__ae_obj({
                    db_instance: db_sponsorships,
                    table_name: 'sponsorship',
                    obj_li: processed_obj_li,
                    properties_to_save: properties_to_save_sponsorship,
                    log_lvl
                });
            }
            return result;
        }
    } catch (e) {}
    return null;
}

// Updated 2026-01-20 to V3
export async function load_ae_obj_li__sponsorship({
    api_cfg,
    for_obj_type = 'account',
    for_obj_id,
    enabled = 'enabled',
    hidden = 'not_hidden',
    limit = 99,
    offset = 0,
    order_by_li = [
        { priority: 'DESC' },
        { sort: 'DESC' },
        { name: 'ASC' },
        { updated_on: 'DESC' }
    ],
    try_cache = true,
    log_lvl = 0
}: {
    api_cfg: any;
    for_obj_type: string;
    for_obj_id: string;
    enabled?: 'enabled' | 'all' | 'not_enabled';
    hidden?: 'hidden' | 'all' | 'not_hidden';
    limit?: number;
    offset?: number;
    order_by_li?: any;
    try_cache?: boolean;
    log_lvl?: number;
}): Promise<ae_Sponsorship[]> {
    if (log_lvl) {
        console.log(
            `*** load_ae_obj_li__sponsorship() *** [V3] for=${for_obj_type}:${for_obj_id}`
        );
    }

    const result_li = await api.get_ae_obj_li({
        api_cfg,
        obj_type: 'sponsorship',
        for_obj_type,
        for_obj_id,
        enabled,
        hidden,
        limit,
        offset,
        order_by_li,
        log_lvl
    });

    if (result_li && try_cache) {
        const processed_obj_li = await process_ae_obj__sponsorship_props({
            obj_li: result_li,
            log_lvl
        });
        await db_save_ae_obj_li__ae_obj({
            db_instance: db_sponsorships,
            table_name: 'sponsorship',
            obj_li: processed_obj_li,
            properties_to_save: properties_to_save_sponsorship,
            log_lvl
        });
    }

    return result_li || [];
}

/**
 * Create a new sponsorship (V3)
 */
export async function create_ae_obj__sponsorship({
    api_cfg,
    data,
    log_lvl = 0
}: {
    api_cfg: any;
    data: any;
    log_lvl?: number;
}) {
    return await api.create_ae_obj({
        api_cfg,
        obj_type: 'sponsorship',
        fields: data,
        log_lvl
    });
}

/**
 * Update sponsorship (V3)
 */
export async function update_ae_obj__sponsorship({
    api_cfg,
    sponsorship_id,
    data,
    log_lvl = 0
}: {
    api_cfg: any;
    sponsorship_id: string;
    data: any;
    log_lvl?: number;
}) {
    return await api.update_ae_obj({
        api_cfg,
        obj_type: 'sponsorship',
        obj_id: sponsorship_id,
        fields: data,
        log_lvl
    });
}

/**
 * Delete sponsorship (V3)
 */
export async function delete_ae_obj__sponsorship({
    api_cfg,
    sponsorship_id,
    log_lvl = 0
}: {
    api_cfg: any;
    sponsorship_id: string;
    log_lvl?: number;
}) {
    return await api.delete_ae_obj({
        api_cfg,
        obj_type: 'sponsorship',
        obj_id: sponsorship_id,
        log_lvl
    });
}

export async function download_export__sponsorship({
    api_cfg,
    account_id,
    file_type = 'CSV',
    filename = 'sponsorship_export.csv',
    params = {},
    log_lvl = 0
}: {
    api_cfg: any;
    account_id: string;
    file_type?: string;
    filename?: string;
    params?: key_val;
    log_lvl?: number;
}) {
    // V2 still used for exports as V3 generic doesn't have a standardized export wrapper yet
    const endpoint = `/v2/crud/sponsorship/list`;
    const query_params = {
        ...params,
        for_obj_type: 'account',
        for_obj_id: account_id,
        file_type,
        return_file: true
    };

    return await api.get_object({
        api_cfg,
        endpoint,
        params: query_params,
        return_blob: true,
        filename,
        auto_download: true,
        log_lvl
    });
}

export const spons_func = {
    load_ae_obj_id__sponsorship_cfg,
    load_ae_obj_id__sponsorship,
    load_ae_obj_li__sponsorship,
    create_ae_obj__sponsorship,
    update_ae_obj__sponsorship,
    delete_ae_obj__sponsorship,
    download_export__sponsorship
};
