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_events } from '$lib/ae_events/db_events';

import { load_ae_obj_li__event_file } from '$lib/ae_events/ae_events__event_file';

const ae_promises: key_val = {};

// Updated 2024-10-08
export async function load_ae_obj_id__event_presenter({
	api_cfg,
	event_presenter_id,
	inc_file_li = false,
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 19,
	offset = 0,
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_presenter_id: string;
	inc_file_li?: boolean;
	enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
	hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
	limit?: number;
	offset?: number;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** load_ae_obj_id__event_presenter() *** event_presenter_id=${event_presenter_id}`
		);
	}

	const params = {};

	ae_promises.load__event_presenter_obj = await api
		.get_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_presenter',
			obj_id: event_presenter_id, // NOTE: This is the FQDN, not normally the ID.
			use_alt_table: true, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
			use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value
			params: params,
			log_lvl: log_lvl
		})
		.then(async function (event_presenter_obj_get_result) {
			if (event_presenter_obj_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_presenter_props({
						obj_li: [event_presenter_obj_get_result],
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('Processed object list:', processed_obj_li);
					}
					// Save the updated results list to the database
					if (log_lvl) {
						console.log('Saving to DB...');
					}
					await db_save_ae_obj_li__ae_obj({
						db_instance: db_events,
						table_name: 'presenter',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}

					// // This is expecting a list
					// db_save_ae_obj_li__event_presenter({
					//     obj_type: 'event_presenter',
					//     obj_li: [event_presenter_obj_get_result]
					// });
				}
				return event_presenter_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_file_li) {
		// Load the files for the presenter
		if (log_lvl) {
			console.log(`Need to load the file list for the presenter now.`);
		}
		const load_event_file_obj_li = load_ae_obj_li__event_file({
			api_cfg: api_cfg,
			for_obj_type: 'event_presenter',
			for_obj_id: event_presenter_id,
			enabled: enabled,
			limit: limit,
			try_cache: try_cache,
			log_lvl: log_lvl
		}).then((event_file_obj_li) => {
			if (log_lvl) {
				console.log(`event_file_obj_li = `, event_file_obj_li);
			}
			return event_file_obj_li;
		});

		if (log_lvl) {
			console.log(`event_file_obj_li = `, load_event_file_obj_li);
		}
		ae_promises.load__event_presenter_obj.event_file_li = load_event_file_obj_li;
	}

	return ae_promises.load__event_presenter_obj;
}

// Updated 2024-10-08
export async function load_ae_obj_li__event_presenter({
	api_cfg,
	for_obj_type,
	for_obj_id,
	inc_file_li = false,
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 19,
	offset = 0,
	order_by_li = {
		priority: 'DESC',
		sort: 'DESC',
		given_name: 'ASC',
		family_name: 'ASC',
		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_file_li?: boolean;
	enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
	hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
	limit?: number;
	offset?: number;
	order_by_li?: key_val;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** load_ae_obj_li__event_presenter() *** for_obj_type=${for_obj_type} for_obj_id=${for_obj_id}`
		);
	}

	// let enabled: string = (params.qry__enabled ?? 'enabled'); // all, disabled, enabled
	// let hidden: string = (params.qry__hidden ?? 'not_hidden'); // all, hidden, not_hidden
	// let limit: number = (params.qry__limit ?? 99); // 99
	// let offset: number = (params.qry__offset ?? 0); // 0

	const params_json: key_val = {};

	// console.log('params_json:', params_json);

	// ae_promises.load__event_presenter_obj_li = await api.get_ae_obj_li_for_obj_id_crud({
	ae_promises.load__event_presenter_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg: api_cfg,
			obj_type: 'event_presenter',
			for_obj_type: for_obj_type,
			for_obj_id: for_obj_id,
			use_alt_tbl: true, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
			// use_alt_mdl: false, // NOTE: This will use the base_name_alt value instead of the base_name value
			enabled: enabled,
			hidden: hidden,
			order_by_li: order_by_li,
			limit: limit,
			offset: offset,
			params_json: params_json,
			params: params,
			log_lvl: log_lvl
		})
		.then(async function (event_presenter_obj_li_get_result) {
			if (event_presenter_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_presenter_props({
						obj_li: event_presenter_obj_li_get_result,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('Processed object list:', processed_obj_li);
					}
					// Save the updated results list to the database
					if (log_lvl) {
						console.log('Saving to DB...');
					}
					await db_save_ae_obj_li__ae_obj({
						db_instance: db_events,
						table_name: 'presenter',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}

					// db_save_ae_obj_li__event_presenter({
					//     obj_type: 'event_presenter',
					//     obj_li: event_presenter_obj_li_get_result
					// });
				}
				return event_presenter_obj_li_get_result;
			} else {
				return [];
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		});

	if (log_lvl) {
		console.log(
			'ae_promises.load__event_presenter_obj_li:',
			ae_promises.load__event_presenter_obj_li
		);
	}

	if (inc_file_li) {
		// Load the files for the presenters
		if (log_lvl) {
			console.log(`Need to load the file list for each presenter now.`);
		}
		for (let i = 0; i < ae_promises.load__event_presenter_obj_li.length; i++) {
			const event_presenter_obj = ae_promises.load__event_presenter_obj_li[i];
			const event_presenter_id = event_presenter_obj.event_presenter_id_random;

			const load_event_file_obj_li = load_ae_obj_li__event_file({
				api_cfg: api_cfg,
				for_obj_type: 'event_presenter',
				for_obj_id: event_presenter_id,
				enabled: enabled,
				limit: limit,
				try_cache: try_cache,
				log_lvl: log_lvl
			}).then((event_file_obj_li) => {
				if (log_lvl) {
					console.log(`event_file_obj_li = `, event_file_obj_li);
				}
				return event_file_obj_li;
			});

			if (log_lvl) {
				console.log(`event_file_obj_li = `, load_event_file_obj_li);
			}
			// ae_promises.load__event_presenter_obj.event_file_li = load_event_file_obj_li;
		}
	}

	return ae_promises.load__event_presenter_obj_li;
}

// Updated 2025-05-23
export async function create_ae_obj__event_presenter({
	api_cfg,
	event_id,
	event_session_id,
	event_presentation_id,
	data_kv,
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_id: string;
	event_session_id: string;
	event_presentation_id: string;
	data_kv: key_val;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** create_ae_obj__event_presenter() *** event_id=${event_id} event_session_id=${event_session_id} event_presentation_id=${event_presentation_id}`
		);
	}

	ae_promises.create__event_presenter = await api
		.create_ae_obj_crud({
			api_cfg: api_cfg,
			obj_type: 'event_presenter',
			fields: {
				event_id_random: event_id,
				event_session_id_random: event_session_id,
				event_presentation_id_random: event_presentation_id,
				...data_kv
			},
			key: api_cfg.api_crud_super_key,
			params: params,
			return_obj: true,
			log_lvl: log_lvl
		})
		.then(async function (event_presenter_obj_create_result) {
			if (event_presenter_obj_create_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_presenter_props({
						obj_li: [event_presenter_obj_create_result],
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('Processed object list:', processed_obj_li);
					}
					// Save the updated results list to the database
					if (log_lvl) {
						console.log('Saving to DB...');
					}
					db_save_ae_obj_li__ae_obj({
						db_instance: db_events,
						table_name: 'presenter',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}

					// db_save_ae_obj_li__event_presenter(
					//     {
					//         obj_type: 'event_presenter', obj_li: [event_presenter_obj_create_result]
					//     });
				}
				return event_presenter_obj_create_result;
			} else {
				return null;
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		})
		.finally(function () {});

	if (log_lvl) {
		console.log('ae_promises.create__event_presenter:', ae_promises.create__event_presenter);
	}
	return ae_promises.create__event_presenter;
}

// Updated 2025-05-23
export async function delete_ae_obj_id__event_presenter({
	api_cfg,
	event_presenter_id,
	method = 'delete', // 'delete', 'disable', 'hide'
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_presenter_id: string;
	method?: string;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** delete_ae_obj_id__event_presenter() *** event_presenter_id=${event_presenter_id}`
		);
	}

	ae_promises.delete__event_presenter_obj = await api
		.delete_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_presenter',
			obj_id: event_presenter_id,
			key: api_cfg.api_crud_super_key,
			params: params,
			method: method,
			log_lvl: log_lvl
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		})
		.finally(function () {
			if (try_cache) {
				if (log_lvl) {
					console.log(
						`Attempting to remove IDB entry for event_presenter_id=${event_presenter_id}`
					);
				}
				db_events.presenter.delete(event_presenter_id);
			}
		});

	if (log_lvl) {
		console.log(
			'ae_promises.delete__event_presenter_obj:',
			ae_promises.delete__event_presenter_obj
		);
	}

	return ae_promises.delete__event_presenter_obj;
}

// Updated 2025-05-23
export async function update_ae_obj__event_presenter({
	api_cfg,
	event_presenter_id,
	data_kv,
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_presenter_id: string;
	data_kv: key_val;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** update_ae_obj__event_presenter() *** event_presenter_id=${event_presenter_id}`,
			data_kv
		);
	}

	ae_promises.update__event_presenter_obj = await api
		.update_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_presenter',
			obj_id: event_presenter_id,
			fields: data_kv,
			key: api_cfg.api_crud_super_key,
			params: params,
			return_obj: true,
			log_lvl: log_lvl
		})
		.then(async function (event_presenter_obj_update_result) {
			if (event_presenter_obj_update_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_presenter_props({
						obj_li: [event_presenter_obj_update_result],
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('Processed object list:', processed_obj_li);
					}
					// Save the updated results list to the database
					if (log_lvl) {
						console.log('Saving to DB...');
					}
					db_save_ae_obj_li__ae_obj({
						db_instance: db_events,
						table_name: 'presenter',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}

					// db_save_ae_obj_li__event_presenter({
					//     obj_type: 'event_presenter',
					//     obj_li: [event_presenter_obj_update_result]
					// });
				}
				return event_presenter_obj_update_result;
			} else {
				return null;
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		})
		.finally(function () {});

	if (log_lvl) {
		console.log(
			'ae_promises.update__event_presenter_obj:',
			ae_promises.update__event_presenter_obj
		);
	}
	return ae_promises.update__event_presenter_obj;
}

// Updated 2025-05-23
export async function search__event_presenter({
	api_cfg,
	event_id,
	agree = null,
	biography = null,
	fulltext_search_qry_str,
	ft_presenter_search_qry_str,
	like_search_qry_str = null,
	like_presentation_search_qry_str = null,
	like_presenter_search_qry_str = null,
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 49,
	offset = 0,
	order_by_li = {
		priority: 'DESC',
		sort: 'DESC',
		given_name: 'ASC',
		family_name: 'ASC',
		email: 'ASC',
		updated_on: 'DESC',
		created_on: 'DESC'
	},
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_id: any;
	agree?: null | boolean;
	biography?: null | boolean;
	fulltext_search_qry_str?: null | string;
	ft_presenter_search_qry_str?: null | string;
	like_search_qry_str?: null | string;
	like_presentation_search_qry_str?: null | string;
	like_presenter_search_qry_str?: null | string;
	enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
	hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
	limit?: number;
	offset?: number;
	order_by_li?: key_val;
	params?: any;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** search__event_presenter() *** event_id=${event_id}`);
	}

	// let enabled: string = (params.qry__enabled ?? 'enabled'); // all, disabled, enabled
	// let hidden: string = (params.qry__hidden ?? 'not_hidden'); // all, hidden, not_hidden
	// let limit: number = (params.qry__limit ?? 25); // 99
	// let offset: number = (params.qry__offset ?? 0); // 0

	const params_json: key_val = {};

	// if (!fulltext_search_qry_str && !like_search_qry_str) {
	//     console.log('No search string provided!!!');
	//     return false; // Returning false instead of [] because no search was performed.
	// }

	if (fulltext_search_qry_str || ft_presenter_search_qry_str) {
		params_json['ft_qry'] = {};
		if (fulltext_search_qry_str && fulltext_search_qry_str.length > 2) {
			params_json['ft_qry']['default_qry_str'] = fulltext_search_qry_str;
		}

		if (ft_presenter_search_qry_str && ft_presenter_search_qry_str.length > 2) {
			params_json['ft_qry']['event_presenter_li_qry_str'] = ft_presenter_search_qry_str;
		}
	}

	// Use the AND (AND LIKE) query
	// if (like_search_qry_str || like_presenter_search_qry_str) {
	//     params_json['and_like'] = {};
	//     if (like_search_qry_str && like_search_qry_str.length > 2) {
	//         params_json['and_like']['default_qry_str'] = like_search_qry_str;
	//     }
	//     if (like_presenter_search_qry_str && like_presenter_search_qry_str.length > 2) {
	//         params_json['and_like']['event_presenter_li_qry_str'] = like_presenter_search_qry_str;
	//     }
	// }

	// Use the AND (OR LIKE) query
	if (like_search_qry_str || like_presentation_search_qry_str || like_presenter_search_qry_str) {
		params_json['or_like'] = {};
		if (like_search_qry_str && like_search_qry_str.length > 2) {
			params_json['or_like']['default_qry_str'] = like_search_qry_str;
		}
		if (like_presentation_search_qry_str && like_presentation_search_qry_str.length > 2) {
			params_json['or_like']['event_presentation_li_qry_str'] = like_presentation_search_qry_str;
		}
		if (like_presenter_search_qry_str && like_presenter_search_qry_str.length > 2) {
			params_json['or_like']['event_presenter_li_qry_str'] = like_presenter_search_qry_str;
		}
	}

	params_json['and_qry'] = {};

	if (agree === true || agree === false) {
		params_json['and_qry']['agree'] = agree;
		// if (!agree) {
		//     params_json['or_qry']['agree'] = null;
		// }
	}
	// if (agree === null) {
	//     params_json['and_qry']['agree'] = agree;
	// }

	if (biography) {
		params_json['and_qry']['biography_check'] = biography;
	}

	// ae_promises.load__event_presenter_obj_li = await api.get_ae_obj_li_for_obj_id_crud({
	ae_promises.load__event_presenter_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg: api_cfg,
			obj_type: 'event_presenter',
			for_obj_type: 'event',
			for_obj_id: event_id,
			use_alt_tbl: true, // NOTE: We want to use the alt table for session searching
			// use_alt_mdl: false,
			enabled: enabled,
			hidden: hidden,
			order_by_li: order_by_li,
			limit: limit,
			offset: offset,
			params_json: params_json,
			params: params,
			log_lvl: log_lvl
		})
		.then(async function (event_presenter_obj_li_get_result) {
			if (event_presenter_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_presenter_props({
						obj_li: event_presenter_obj_li_get_result,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('Processed object list:', processed_obj_li);
					}
					// Save the updated results list to the database
					if (log_lvl) {
						console.log('Saving to DB...');
					}
					await db_save_ae_obj_li__ae_obj({
						db_instance: db_events,
						table_name: 'presenter',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}
				}
				return event_presenter_obj_li_get_result;
			} else {
				return [];
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		})
		.finally(function () {});

	if (log_lvl) {
		console.log(
			'ae_promises.load__event_presenter_obj_li:',
			ae_promises.load__event_presenter_obj_li
		);
	}
	return ae_promises.load__event_presenter_obj_li;
}

// Updated 2024-08-07
export async function email_sign_in__event_presenter({
	api_cfg,
	to_email,
	to_name,
	base_url,
	person_id,
	person_passcode,
	event_id,
	event_session_id,
	event_presentation_id,
	event_presenter_id,
	session_name,
	presentation_name,
	log_lvl = 0
}: {
	api_cfg: any;
	to_email: string;
	to_name: string;
	base_url: string;
	person_id: string;
	person_passcode: string;
	event_id: string;
	event_session_id: string;
	event_presentation_id: string;
	event_presenter_id: string;
	session_name: string;
	presentation_name: string;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** email_sign_in__event_presenter() *** to_email=${to_email} to_name=${to_name} person_id=${person_id} person_passcode=${person_passcode} presentation_id=${event_presentation_id} presenter_id=${event_presenter_id}`
		);
	}

	const subject = `LCI Congress 2025 - Pres Mgmt Hub Sign In Link for ${session_name} (ID: ${event_session_id})`;

	const sign_in_url = encodeURI(
		`${base_url}/events/${event_id}/session/${event_session_id}?person_id=${person_id}&person_pass=${person_passcode}&presentation_id=${event_presentation_id}&presenter_id=${event_presenter_id}`
	);

	const body_html = `
    <div>${to_name},
    <p>Your link to sign into the presentation management hub for LCI Congress 2025 is below. If you did not request this, please delete and ignore this email. If you need to make any changes or updates to your submission, you may use this link again later.</p>
    </div>

    <div>
    <strong>27th Annual Lean Construction Congress (2025)</strong>:<br>
    <p>
    Session Name: ${session_name}<br>
    Session ID: ${event_session_id}<br>
    Presentation Name: ${presentation_name}<br>
    Presentation ID: ${event_presentation_id}
    </p>
    <p>Use this link to view or update your LCI 2025 presentation information.<br>
    Copy and paste link: <a href="${sign_in_url}">${sign_in_url}</a></p>
    </div>`;

	api.send_email({
		api_cfg: api_cfg,
		from_email: 'noreply+presmgmt@oneskyit.com',
		from_name: 'LCI 2025 Pres Mgmt Hub',
		to_email: to_email,
		subject: subject,
		body_html: body_html
	});
}

// Updated 2025-05-23
export const properties_to_save = [
	'id',
	'event_presenter_id',
	// 'event_presenter_id_random',

	'external_id',
	'code',

	// 'for_type',
	// 'for_id',
	// 'for_id_random',

	'event_id',
	// 'event_id_random',
	'event_session_id',
	// 'event_session_id_random',
	'event_presentation_id',
	// 'event_presentation_id_random',
	'event_person_id',
	// 'event_person_id_random',
	'person_id',
	// 'person_id_random',
	'person_profile_id',
	// 'person_profile_id_random',

	'pronouns',
	'informal_name',
	'title_names',
	'given_name',
	'middle_name',
	'family_name',
	'designations',

	'professional_title',

	'full_name',

	'affiliations',

	'email',

	'biography',

	'agree',
	'comments',

	'passcode',

	'hide_event_launcher',

	'data_json',

	'enable',
	'hide',
	'priority',
	'sort',
	'group',
	'notes',
	'created_on',
	'updated_on',

	// Generated fields for sorting locally only
	'tmp_sort_1',
	'tmp_sort_2',
	// 'tmp_sort_a',
	// 'tmp_sort_b',

	// From SQL view
	'file_count',

	'event_session_code',
	'event_session_name',
	'event_session_start_datetime',
	'event_presentation_code',
	'event_presentation_name',
	'event_presentation_start_datetime',

	'person_external_id',
	'person_external_sys_id',
	'person_given_name',
	'person_family_name',
	'person_full_name',
	'person_professional_title',
	'person_affiliations',
	'person_primary_email',
	'person_passcode'
];

/**
 * 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 };

		// --- Common Transformations ---

		// 1. Standardize ID and other '_random' fields
		// The API often returns fields like 'person_id_random', which need to be aliased to 'person_id'.
		for (const key in processed_obj) {
			if (key.endsWith('_random')) {
				const newKey = key.slice(0, -7); // Remove '_random' suffix
				processed_obj[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 for client-side sorting.
		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}`;

		// --- Specific Transformations ---
		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-05-23
export async function process_ae_obj__event_presenter_props({
	obj_li,
	log_lvl = 0
}: {
	obj_li: any[];
	log_lvl?: number;
}) {
	return _process_generic_props({
		obj_li,
		obj_type: 'event_presenter',
		log_lvl,
		specific_processor: (obj) => {
			// Event presenter-specific computed sort fields, overriding generic ones if needed
			obj.tmp_sort_1 = `${obj.group ?? ''}_${obj.priority ? '1' : '0'}_${
				obj.sort?.toString().padStart(3, '0') ?? ''
			}_${obj.updated_on ?? obj.created_on}`;
			obj.tmp_sort_2 = `${obj.group ?? ''}_${obj.priority ? '1' : '0'}_${
				obj.sort?.toString().padStart(3, '0') ?? ''
			}_${obj.updated_on}_${obj.created_on}`;

			return obj;
		}
	});
}
