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

export async function download_export__obj_type({
    api_cfg,
    get_obj_type, // The type of object to return: event_badge, event_presenter, sponsorship, etc.
    for_obj_type, // Usually for an account, event, event_exhibit, or sponsorship_cfg
    for_obj_id, // The ID of the object
    exp_alt = null, // Export name (idaa, other, not 'default')
    file_type = 'CSV', // 'CSV' or 'Excel'
    return_file = true,
    filename = 'no_filename.csv',
    auto_download = false,
    limit = 5000,
    params = {}, // key value object is expected
    log_lvl = 0
}: {
    api_cfg: any;
    get_obj_type: string;
    for_obj_type: string;
    for_obj_id: string;
    exp_alt?: null | string;
    file_type?: string;
    return_file?: boolean;
    filename?: string;
    auto_download?: boolean;
    limit?: number;
    params?: key_val;
    log_lvl?: number;
}) {
    const endpoint = `/v2/crud/${get_obj_type}/list`;
    params['for_obj_type'] = for_obj_type;
    params['for_obj_id'] = for_obj_id;

    if (file_type == 'CSV' || file_type == 'Excel') {
        params['file_type'] = file_type;
    }
    params['return_file'] = true;
    params['mdl_alt'] = 'out';

    if (exp_alt) {
        params['exp_alt'] = exp_alt;
    }

    const clean_filename = filename.replace(/[^a-zA-Z0-9\[\]-_.]/gi, '_');

    if (limit >= 0) {
        params['limit'] = limit;
    }

    const result = await api.get_object({
        api_cfg: api_cfg,
        endpoint: endpoint,
        params: params,
        timeout: 90000, // Seems to timeout sometimes with the default of 60 seconds
        return_blob: return_file,
        filename: clean_filename,
        auto_download: auto_download,
        task_id: for_obj_id,
        log_lvl: log_lvl
    });

    if (log_lvl) {
        console.log('download_export__obj_type result:', result);
    }

    return result;
}
