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';
import { load_ae_obj_li__event_presentation } from '$lib/ae_events/ae_events__event_presentation';

const ae_promises: key_val = {};

// Updated 2025-05-22
export async function load_ae_obj_id__event_session({
	api_cfg,
	event_session_id,
	inc_file_li = false,
	inc_all_file_li = false,
	inc_presentation_li = false,
	inc_presenter_li = false,
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 149,
	offset = 0,
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_session_id: string;
	inc_file_li?: boolean;
	inc_all_file_li?: boolean;
	inc_presentation_li?: boolean;
	inc_presenter_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_session() *** event_session_id=${event_session_id}`);
	}

	const params = {};

	// $events_sess.badges.status_load__event_session_obj = 'loading';
	ae_promises.load__event_session_obj = await api
		.get_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_session',
			obj_id: event_session_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 in the API config.
			params: params,
			log_lvl: log_lvl
		})
		.then(async function (event_session_obj_get_result) {
			if (event_session_obj_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_session_props({
						obj_li: [event_session_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: 'session',
						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_session({
					//     obj_type: 'event_session',
					//     obj_li: [event_session_obj_get_result]
					// });
				}
				return event_session_obj_get_result;
			} else {
				console.log('No results returned.');
				return null;
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		});

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

	if (ae_promises?.load__event_session_obj === null) {
		console.log('No results returned.');
		return null;
	}

	if (inc_file_li) {
		// Load the files for the session
		if (log_lvl) {
			console.log(`Need to load the file list for the session now`);
		}
		const load_event_file_obj_li = load_ae_obj_li__event_file({
			api_cfg: api_cfg,
			for_obj_type: 'event_session',
			for_obj_id: event_session_id,
			enabled: enabled,
			limit: 15,
			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(`load_event_file_obj_li = `, load_event_file_obj_li);
		}
		ae_promises.load__event_session_obj.event_file_li = load_event_file_obj_li;
	}

	if (inc_presentation_li) {
		// Load the presentations for the session
		if (log_lvl) {
			console.log(`Need to load the presentation list for the session now`);
		}
		// NOTE: The files will only be included if inc_all_file_li is true. 2025-09-17
		const load_event_presentation_obj_li = load_ae_obj_li__event_presentation({
			api_cfg: api_cfg,
			for_obj_type: 'event_session',
			for_obj_id: event_session_id,
			inc_file_li: inc_all_file_li,
			inc_presenter_li: inc_presenter_li,
			enabled: enabled, // all, disabled, enabled
			hidden: hidden, // all, hidden, not_hidden
			limit: limit, // 25
			offset: offset, // 0
			params: {},
			try_cache: try_cache,
			log_lvl: log_lvl
		}).then((event_presentation_obj_li) => {
			if (log_lvl) {
				console.log(`event_presentation_obj_li = `, event_presentation_obj_li);
			}
			return event_presentation_obj_li;
		});

		if (log_lvl) {
			console.log(`event_presentation_obj_li = `, load_event_presentation_obj_li);
		}
		ae_promises.load__event_session_obj.event_presentation_li = load_event_presentation_obj_li;
	}

	return ae_promises.load__event_session_obj;
}

// Updated 2025-05-22
export async function load_ae_obj_li__event_session({
	api_cfg,
	for_obj_type,
	for_obj_id,
	inc_file_li = false,
	inc_all_file_li = false,
	inc_presentation_li = false,
	inc_presenter_li = false,
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 149,
	offset = 0,
	order_by_li = {
		priority: 'DESC',
		sort: 'DESC',
		start_datetime: 'ASC',
		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;
	inc_all_file_li?: boolean;
	inc_presentation_li?: boolean;
	inc_presenter_li?: boolean;
	enabled?: 'enabled' | 'all' | 'not_enabled' | undefined; // all, disabled, enabled
	hidden?: 'hidden' | 'all' | 'not_hidden' | undefined; // all, hidden, not_hidden
	limit?: number; // 99
	offset?: number; // 0
	order_by_li?: key_val;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** load_ae_obj_li__event_session() *** 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_session_obj_li = await api.get_ae_obj_li_for_obj_id_crud({
	ae_promises.load__event_session_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg: api_cfg,
			obj_type: 'event_session',
			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_session_obj_li_get_result) {
			if (event_session_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_session_props({
						obj_li: event_session_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: 'session',
						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_session({
					//     obj_type: 'event_session',
					//     obj_li: event_session_obj_li_get_result
					// });
				}
				return event_session_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_session_obj_li:', ae_promises.load__event_session_obj_li);
	}

	if (inc_file_li) {
		// Load the files for the sessions
		if (log_lvl) {
			console.log(`Need to load the file list for each session now`);
		}
		for (let i = 0; i < ae_promises.load__event_session_obj_li.length; i++) {
			const event_session_obj = ae_promises.load__event_session_obj_li[i];
			const event_session_id = event_session_obj.event_session_id_random;

			const load_event_file_obj_li = load_ae_obj_li__event_file({
				api_cfg: api_cfg,
				for_obj_type: 'event_session',
				for_obj_id: event_session_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(`load_event_file_obj_li = `, load_event_file_obj_li);
			}
		}
	}

	if (inc_presentation_li) {
		// Load the presentations for the sessions
		if (log_lvl) {
			console.log(`Need to load the presentation list for each session now`);
		}
		for (let i = 0; i < ae_promises.load__event_session_obj_li.length; i++) {
			const event_session_obj = ae_promises.load__event_session_obj_li[i];
			const event_session_id = event_session_obj.event_session_id_random;

			// NOTE: The files will only be included if inc_all_file_li is true. 2025-09-17
			const load_event_presentation_obj_li = load_ae_obj_li__event_presentation({
				api_cfg: api_cfg,
				for_obj_type: 'event_session',
				for_obj_id: event_session_id,
				inc_file_li: inc_all_file_li,
				inc_presenter_li: inc_presenter_li,
				enabled: enabled,
				hidden: hidden,
				limit: limit,
				offset: offset,
				params: params,
				try_cache: try_cache,
				log_lvl: log_lvl
			}).then((event_presentation_obj_li) => {
				if (log_lvl) {
					console.log(`event_presentation_obj_li = `, event_presentation_obj_li);
				}
				// if (try_cache) {
				//     console.log(`event_session_obj = `, event_session_obj);
				//     event_session_obj.event_presentation_li = event_presentation_obj_li;
				//     // Re-save the session object with the new presentation list
				//     db_save_ae_obj_li__event_session({
				//         obj_type: 'event_session',
				//         obj_li: event_session_obj
				//     });
				// }

				return event_presentation_obj_li;
			});

			if (log_lvl) {
				console.log(`load_event_presentation_obj_li = `, load_event_presentation_obj_li);
			}
		}
	}

	return ae_promises.load__event_session_obj_li;
}

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

	ae_promises.create__event_session = await api
		.create_ae_obj_crud({
			api_cfg: api_cfg,
			obj_type: 'event_session',
			fields: {
				event_id_random: event_id,
				...data_kv
			},
			key: api_cfg.api_crud_super_key,
			params: params,
			return_obj: true,
			log_lvl: log_lvl
		})
		.then(async function (event_session_obj_create_result) {
			if (event_session_obj_create_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_session_props({
						obj_li: [event_session_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: 'session',
						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_session(
					//     {
					//         obj_type: 'event_session',
					//         obj_li: [event_session_obj_create_result]
					//     });
				}
				return event_session_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_session:', ae_promises.create__event_session);
	}
	return ae_promises.create__event_session;
}

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

	ae_promises.delete__event_session_obj = await api
		.delete_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_session',
			obj_id: event_session_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_session_id=${event_session_id}`);
				}
				db_events.session.delete(event_session_id);
			}
		});

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

	return ae_promises.delete__event_session_obj;
}

// Updated 2025-05-22
export async function update_ae_obj__event_session({
	api_cfg,
	event_session_id,
	data_kv,
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_session_id: string;
	data_kv: key_val;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** update_ae_obj__event_session() *** event_session_id=${event_session_id}`,
			data_kv
		);
	}
	// ae_promises.update__event_session_obj = 'test';
	ae_promises.update__event_session_obj = await api
		.update_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_session',
			obj_id: event_session_id,
			fields: data_kv,
			key: api_cfg.api_crud_super_key,
			params: params,
			return_obj: true,
			log_lvl: log_lvl
		})
		.then(async function (event_session_obj_update_result) {
			if (event_session_obj_update_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_session_props({
						obj_li: [event_session_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: 'session',
						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_session({
					//     obj_type: 'event_session', obj_li: [event_session_obj_update_result]
					// });
				}
				return event_session_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_session_obj:', ae_promises.update__event_session_obj);
	}
	return ae_promises.update__event_session_obj;
}

// This new function is using CRUD v2. This should allow for more flexibility in the queries.
// Updated 2025-07-21
export async function qry__event_session({
	api_cfg,
	event_id,
	qry_str,
	qry_files,
	qry_start_datetime, // Example greater than: '2024-10-24'
	qry_poc_agree = null,
	qry_poc_kv_json,
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 49,
	offset = 0,
	order_by_li = {
		priority: 'DESC',
		sort: 'DESC',
		start_datetime: 'ASC',
		name: 'ASC',
		updated_on: 'DESC',
		created_on: 'DESC'
	},
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_id: any;
	qry_str?: string;
	qry_files?: null | boolean;
	qry_start_datetime?: null | string; // Greater than this datetime
	qry_poc_agree?: null | boolean;
	qry_poc_kv_json?: null | boolean; // Key value pairs for the point of contact
	enabled?: 'enabled' | 'all' | 'not_enabled' | undefined; // all, disabled, enabled
	hidden?: 'hidden' | 'all' | 'not_hidden' | undefined; // all, hidden, not_hidden
	limit?: number;
	offset?: number;
	order_by_li?: key_val;
	params?: any;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** qry__event_session() *** event_id=${event_id} qry_str=${qry_str}`);
	}

	const params_json: key_val = {};

	params_json['qry'] = [];

	if (qry_files === true) {
		const qry_param = {
			type: 'AND',
			field: 'file_count_all',
			operator: '>',
			value: 0
		};
		params_json['qry'].push(qry_param);
	} else if (qry_files === false) {
		const qry_param = {
			type: 'AND',
			field: 'file_count_all',
			operator: 'IS',
			value: null
		};
		params_json['qry'].push(qry_param);
	}

	if (qry_start_datetime) {
		const qry_param = {
			type: 'AND',
			field: 'start_datetime',
			operator: '>',
			value: qry_start_datetime
		};
		params_json['qry'].push(qry_param);
	}

	if (qry_poc_agree === true) {
		const qry_param = {
			type: 'AND',
			field: 'poc_agree',
			operator: '=',
			value: true
		};
		params_json['qry'].push(qry_param);
	} else if (qry_poc_agree === false) {
		// let qry_param =
		//     {
		//         type: "AND",
		//         field: "poc_agree",
		//         operator: "IS",
		//         value: null
		//     };
		// params_json['qry'].push(qry_param);
		const qry_param = {
			type: 'AND',
			field: 'poc_agree',
			operator: '=',
			value: false
		};
		params_json['qry'].push(qry_param);
	}

	if (qry_poc_kv_json === true) {
		const qry_param = {
			type: 'AND',
			field: 'poc_kv_json',
			operator: 'IS NOT',
			value: null
		};
		params_json['qry'].push(qry_param);
	} else if (qry_poc_kv_json === false) {
		const qry_param = {
			type: 'AND',
			field: 'poc_kv_json',
			operator: 'IS',
			value: null
		};
		params_json['qry'].push(qry_param);
	}

	ae_promises.load__event_session_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg: api_cfg,
			obj_type: 'event_session',
			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,
			use_alt_exp: 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_session_obj_li_get_result) {
			if (event_session_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_session_props({
						obj_li: event_session_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_session({
					//     obj_type: 'event_session',
					//     obj_li: event_session_obj_li_get_result
					// });
				}
				return event_session_obj_li_get_result;
			} else {
				return [];
			}
		});

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

// Updated 2025-05-22
export async function search__event_session({
	api_cfg,
	event_id,
	poc_agree = 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,
	like_poc_name_qry_str = null,
	file_count = false, // If true then only show those that have a file count
	location_name = null,
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 49,
	offset = 0,
	order_by_li = {
		priority: 'DESC',
		sort: 'DESC',
		start_datetime: 'ASC',
		name: 'ASC',
		updated_on: 'DESC',
		created_on: 'DESC'
	},
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_id: any;
	poc_agree?: 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;
	like_poc_name_qry_str?: null | string;
	file_count?: boolean;
	location_name?: null | string;
	enabled?: 'enabled' | 'all' | 'not_enabled' | undefined; // all, disabled, enabled
	hidden?: 'hidden' | 'all' | 'not_hidden' | undefined; // all, hidden, not_hidden
	limit?: number;
	offset?: number;
	order_by_li?: key_val;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** search__event_session() *** event_id=${event_id} like_search_qry_str=${like_search_qry_str} location_name=${location_name}`
		);
	}

	// 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 ||
		like_poc_name_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;
		}
		if (like_poc_name_qry_str && like_poc_name_qry_str.length > 2) {
			params_json['or_like']['poc_person_full_name'] = like_poc_name_qry_str;
		}
	}

	params_json['and_qry'] = {};

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

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

	// This should be using a like with surrounded by %'s
	if (location_name) {
		params_json['and_qry']['event_location_name'] = location_name;
	}

	// let order_by_li = {'priority': 'DESC', 'sort': 'DESC', 'start_datetime': 'ASC', 'name': 'ASC', 'updated_on': 'DESC', 'created_on': 'DESC'};

	// ae_promises.load__event_session_obj_li = await api.get_ae_obj_li_for_obj_id_crud({
	ae_promises.load__event_session_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg: api_cfg,
			obj_type: 'event_session',
			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_session_obj_li_get_result) {
			if (event_session_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_session_props({
						obj_li: event_session_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: 'session',
						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_session({
					//     obj_type: 'event_session',
					//     obj_li: event_session_obj_li_get_result
					// });
				}
				return event_session_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_session_obj_li:', ae_promises.load__event_session_obj_li);
	}
	return ae_promises.load__event_session_obj_li;
}

// This function will loop through the event_session_obj_li and save each one to the DB.
// Updated 2025-05-09
export async function db_save_ae_obj_li__event_session({
	obj_type,
	obj_li,
	log_lvl = 0
}: {
	obj_type: string;
	obj_li: any;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** db_save_ae_obj_li__event_session() *** obj_type=${obj_type}`, obj_li);
	}

	if (obj_li && obj_li.length) {
		const obj_li_id: string[] = [];

		for (const obj of obj_li) {
			if (log_lvl) {
				console.log(`Processing ae_obj ${obj_type}:`, obj);
			}

			const obj_record = {
				id: obj.event_session_id_random,
				event_session_id: obj.event_session_id_random,
				event_session_id_random: obj.event_session_id_random,

				external_id: obj.external_id,
				code: obj.code,

				for_type: obj.for_type,
				for_id: obj.for_id_id_random,
				for_id_random: obj.for_id_random,

				type_code: obj.type_code,

				event_id: obj.event_id_random,
				event_id_random: obj.event_id_random,
				event_location_id: obj.event_location_id_random,
				event_location_id_random: obj.event_location_id_random,

				poc_person_id: obj.poc_person_id_random,
				poc_person_id_random: obj.poc_person_id_random,
				poc_agree: obj.poc_agree,
				poc_kv_json: obj.poc_kv_json ?? {},

				name: obj.name,
				description: obj.description,

				start_datetime: obj.start_datetime,
				end_datetime: obj.end_datetime,

				passcode: obj.passcode,

				hide_event_launcher: obj.hide_event_launcher,

				alert: obj.alert,
				alert_msg: obj.alert_msg,

				data_json: obj.data_json,

				ux_mode: obj.ux_mode,

				enable: obj.enable,
				hide: obj.hide,
				priority: obj.priority,
				sort: obj.sort,
				group: obj.group,
				notes: obj.notes,
				created_on: obj.created_on,
				updated_on: obj.updated_on,

				// From SQL view
				file_count: obj.file_count,
				file_count_all: obj.file_count_all,
				internal_use_count: obj.internal_use_count,
				event_file_id_li_json: obj.event_file_id_li_json,

				poc_person_given_name: obj.poc_person_given_name,
				poc_person_family_name: obj.poc_person_family_name,
				poc_person_full_name: obj.poc_person_full_name,
				poc_person_primary_email: obj.poc_person_primary_email,
				poc_person_passcode: obj.poc_person_passcode,

				event_name: obj.event_name,

				event_location_code: obj.event_location_code,
				event_location_name: obj.event_location_name,

				// A key value list of the presentations
				event_presentation_kv: obj.event_presentation_kv,
				event_presentation_li: obj.event_presentation_li
			};

			let id_random = null;

			try {
				id_random = await db_events.session.update(obj_record.id, obj_record);
			} catch (error) {
				console.error(`Error: Failed to update ${obj_record.id}: ${error}`);
			}

			if (!id_random) {
				if (log_lvl) {
					console.log(`Failed to update record with ID: ${obj_record.id}. Trying put...`);
				}
				try {
					id_random = await db_events.session.put(obj_record);
				} catch (error) {
					console.error(`Error: Failed to put ${obj.event_session_id_random}: ${error}`);
				}
			} else {
				if (log_lvl) {
					console.log(`Updated record with ID: ${obj_record.id}`);
				}
			}

			if (!id_random) {
				console.error(`Failed to save record with ID: ${obj_record.id}`);
			} else {
				if (log_lvl) {
					console.log(`Saved record with ID: ${obj_record.id}`);
				}
				obj_li_id.push(obj_record.id);
			}
		}

		return obj_li_id;
	} else {
		if (log_lvl) {
			console.log('No objects to save.');
		}
		return [];
	}
}

// This is intended for the Point of Contact (POC) for the session.
// Updated 2024-07-01
export async function email_sign_in__event_session({
	api_cfg,
	to_email,
	to_name,
	base_url,
	person_id,
	person_passcode,
	event_id,
	event_session_id,
	session_name
}: {
	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;
	session_name: string;
}) {
	console.log(
		`*** email_sign_in__event_session() *** to_email=${to_email} to_name=${to_name} person_id=${person_id} person_passcode=${person_passcode} session_id=${event_session_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}&session_id=${event_session_id}`
	);

	const body_html = `
    <div>${to_name},
    <p>Your link to sign into the presentation management hub as a session Champion 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}
    </p>
    <p>Use this link to view or update your LCI 2025 session 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-09
export const properties_to_save = [
	'id',
	'event_session_id',
	// 'event_session_id_random',

	'external_id',
	'code',

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

	'type_code',

	'event_id',
	// 'event_id_random',
	'event_location_id',
	// 'event_location_id_random',

	'poc_person_id',
	// 'poc_person_id_random',
	'poc_agree',
	'poc_kv_json',

	'name',
	'description',

	'start_datetime',
	'end_datetime',

	'passcode',

	'hide_event_launcher',

	'alert',
	'alert_msg',

	'data_json',

	'ux_mode',

	'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',
	'file_count_all',
	'internal_use_count',
	'event_file_id_li_json',

	'poc_person_given_name',
	'poc_person_family_name',
	'poc_person_full_name',
	'poc_person_primary_email',
	'poc_person_passcode',

	'event_name',

	'event_location_code',
	'event_location_name',

	// A key value list of the presentations
	'event_presentation_kv',
	'event_presentation_li'
];

/**
 * 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-09
export async function process_ae_obj__event_session_props({
	obj_li,
	log_lvl = 0
}: {
	obj_li: any[];
	log_lvl?: number;
}) {
	return _process_generic_props({
		obj_li,
		obj_type: 'event_session',
		log_lvl,
		specific_processor: (obj) => {
			// Event session-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;
		}
	});
}
