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';

const ae_promises: key_val = {};

// Updated 2025-07-21
export async function load_ae_obj_id__event_file({
	api_cfg,
	event_file_id,
	try_cache = false,
	log_lvl = 0
}: {
	api_cfg: any;
	event_file_id: string;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** load_ae_obj_id__event_file() *** event_file_id=${event_file_id}`);
	}

	const params = {};

	ae_promises.load__event_file_obj = await api
		.get_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_file',
			obj_id: event_file_id, // NOTE: This is the FQDN, not normally the ID.
			use_alt_table: false, // 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_file_obj_get_result) {
			if (event_file_obj_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_file_props({
						obj_li: [event_file_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: 'file',
						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_file({obj_type: 'event_file', obj_li: [event_file_obj_get_result]});
				}
				return event_file_obj_get_result;
			} else {
				console.log('No results returned.');
				return null;
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		});

	return ae_promises.load__event_file_obj;
}

// Updated 2025-07-21
export async function load_ae_obj_li__event_file({
	api_cfg,
	for_obj_type,
	for_obj_id,
	enabled = 'enabled',
	hidden = 'not_hidden',
	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;
	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_file() *** for_obj_type=${for_obj_type} for_obj_id=${for_obj_id}`
		);
	}

	// Check if for_obj_type is in the list of valid Aether object types:
	const valid_for_obj_types = [
		'event',
		'event_session',
		'event_presentation',
		'event_presenter',
		'event_location',
		'event_badge',
		'event_device'
	];
	if (!valid_for_obj_types.includes(for_obj_type)) {
		console.log(`Invalid for_obj_type: ${for_obj_type}`);
		return [];
	}

	const params_json: key_val = {};

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

	ae_promises.load__event_file_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg: api_cfg,
			obj_type: 'event_file',
			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
			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_file_obj_li_get_result) {
			if (event_file_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_file_props({
						obj_li: event_file_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: 'file',
						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_file({obj_type: 'event_file', obj_li: event_file_obj_li_get_result});
				}
				return event_file_obj_li_get_result;
			} else {
				console.log('No results returned.');
				return [];
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		});

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

// Updated 2025-07-21
// This may need to be reviewed again???
export async function create_event_file_obj_from_hosted_file_async({
	api_cfg,
	hosted_file_id,
	params = {},
	data = {},
	return_obj = false,
	inc_hosted_file = false,
	return_meta = false,
	log_lvl = 0
}: {
	api_cfg: any;
	hosted_file_id: string;
	params?: key_val;
	data?: key_val;
	return_obj?: boolean;
	inc_hosted_file?: boolean;
	return_meta?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** create_event_file_obj_from_hosted_file_async() *** hosted_file_id=${hosted_file_id}`
		);
	}

	if (!hosted_file_id) {
		console.log(`ERROR: Events Launcher - Event File - hosted_file_id required to create`);
		return false;
	}

	const endpoint = `/event/file/from_hosted_file/${hosted_file_id}`;
	if (return_obj) {
		params['return_obj'] = true;
	}
	if (inc_hosted_file) {
		params['inc_hosted_file'] = true;
	}
	const event_file_obj_post_promise = await api
		.post_object({
			api_cfg: api_cfg,
			endpoint: endpoint,
			params: params,
			data: data,
			// return_obj: return_obj,
			return_meta: return_meta,
			log_lvl: log_lvl
		})
		.then(function (result) {
			console.log('POST DONE create_event_file_obj_from_hosted_file');
			console.log(result);
			return result;
		})
		.catch(function (error: any) {
			console.log(error);
			return false; // Returning false since something may have gone wrong. Also more in line with what the API returns.
			// return error;
		});

	// console.log(event_file_obj_post_promise);
	if (return_obj) {
		return event_file_obj_post_promise;
	} else {
		return event_file_obj_post_promise.event_file_id_random;
	}
}

// Updated 2025-07-21
export async function delete_ae_obj_id__event_file({
	api_cfg,
	event_file_id,
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_file_id: string;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** delete_ae_obj_id__event_file() *** event_file_id=${event_file_id}`);
	}

	const endpoint = `/event/file/${event_file_id}/v2`;

	params['delete_hosted_file'] = true; // This does not actually delete the hosted file from the server.
	params['rm_orphan'] = true; // This is what actually allows the hosted file to be deleted from the server.

	ae_promises.delete__event_file_obj = await api
		.delete_object({
			api_cfg: api_cfg,
			endpoint: endpoint,
			params: params,
			// return_meta: return_meta,
			log_lvl: log_lvl
		})
		.finally(function () {
			if (try_cache) {
				if (log_lvl) {
					console.log(`Attempting to remove IDB entry for event_file_id=${event_file_id}`);
				}
				db_events.file.delete(event_file_id); // Delete from the DB no matter what.
			}
		});

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

	return ae_promises.delete__event_file_obj;
}

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

	// Perform the API update
	const result = await api.update_ae_obj_id_crud({
		api_cfg: api_cfg,
		obj_type: 'event_file',
		obj_id: event_file_id, // NOTE: This is the FQDN, not normally the ID.
		fields: data_kv,
		key: api_cfg.api_crud_super_key,
		params: params,
		return_obj: true,
		log_lvl: log_lvl
	});
	// Handle the result
	if (result) {
		if (try_cache) {
			// Process the results first
			const processed_obj_li = await process_ae_obj__event_file_props({
				obj_li: [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: 'file',
				obj_li: processed_obj_li,
				properties_to_save: properties_to_save,
				log_lvl: log_lvl
			});
			if (log_lvl) {
				console.log('DB save completed.');
			}

			// await db_save_ae_obj_li__event_file({
			//     obj_type: 'event_file',
			//     obj_li: [result],
			//     log_lvl: log_lvl,
			// });
		}
		return result;
	} else {
		console.error('Failed to update event file.');
		return null;
	}
}

// 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_file({
	api_cfg,
	event_id,
	qry_created_on = null, // Example greater than: '2024-10-24'
	qry_min_file_size = null,
	qry_file_purpose = null,
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 49,
	offset = 0,
	order_by_li = {
		priority: 'DESC',
		sort: 'DESC',
		created_on: 'DESC',
		updated_on: 'DESC',
		filename: 'ASC',
		extension: 'ASC',
		hosted_file_size: 'ASC'
	},
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_id: any;
	qry_created_on?: null | string;
	qry_min_file_size?: null | number;
	qry_file_purpose?: 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(`*** qry__event_file() *** event_id=${event_id}`);
	}

	const params_json: key_val = {};

	params_json['qry'] = [];

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

	if (qry_min_file_size) {
		// console.log('qry_min_file_size:', qry_min_file_size);
		const qry_param = {
			type: 'AND',
			field: 'hosted_file_size',
			operator: '>',
			value: qry_min_file_size
		};
		params_json['qry'].push(qry_param);
	}

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

	// if (!limit || limit <= 0) {
	//     limit = null;
	// }

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

	ae_promises.load__event_file_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg: api_cfg,
			obj_type: 'event_file',
			for_obj_type: 'event',
			for_obj_id: event_id,
			use_alt_tbl: true, // NOTE: We want to use the alt table for file 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(function (event_file_obj_li_get_result) {
			if (event_file_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					process_ae_obj__event_file_props({
						obj_li: event_file_obj_li_get_result,
						log_lvl: log_lvl
					}).then(async function (processed_obj_li) {
						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: 'file',
							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_file({obj_type: 'event_file', obj_li: event_file_obj_li_get_result});
				return event_file_obj_li_get_result;
			} else {
				return [];
			}
		});

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

// Updated 2025-07-21
export async function search__event_file({
	api_cfg,
	event_id,
	created_on = null,
	min_file_size = null,
	fulltext_search_qry_str,
	ft_file_search_qry_str,
	like_search_qry_str = null,
	like_presentation_search_qry_str = null,
	like_file_search_qry_str = null,
	order_by_li = {
		priority: 'DESC',
		sort: 'DESC',
		created_on: 'DESC',
		updated_on: 'DESC',
		filename: 'ASC',
		extension: 'ASC',
		hosted_file_size: 'ASC'
	},
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_id: any;
	created_on?: null | string;
	min_file_size?: null | number;
	fulltext_search_qry_str?: null | string;
	ft_file_search_qry_str?: null | string;
	like_search_qry_str?: null | string;
	like_presentation_search_qry_str?: null | string;
	like_file_search_qry_str?: null | string;
	order_by_li?: key_val;
	params?: any;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** search__event_file() *** event_id=${event_id}`);
	}

	const enabled: string = params.qry__enabled ?? 'enabled'; // all, disabled, enabled
	const hidden: string = params.qry__hidden ?? 'not_hidden'; // all, hidden, not_hidden
	const limit: number = params.qry__limit ?? 25; // 99
	const 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_file_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_file_search_qry_str && ft_file_search_qry_str.length > 2) {
			params_json['ft_qry']['event_file_li_qry_str'] = ft_file_search_qry_str;
		}
	}

	// Use the AND (AND LIKE) query
	// if (like_search_qry_str || like_file_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_file_search_qry_str && like_file_search_qry_str.length > 2) {
	//         params_json['and_like']['event_file_li_qry_str'] = like_file_search_qry_str;
	//     }
	// }

	// Use the AND (OR LIKE) query
	// if (like_search_qry_str || like_presentation_search_qry_str || like_file_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_file_search_qry_str && like_file_search_qry_str.length > 2) {
	//         params_json['or_like']['event_file_li_qry_str'] = like_file_search_qry_str;
	//     }
	// }

	// params_json['and_qry'] = {};

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

	if (min_file_size) {
		params_json['and_qry'] = { hosted_file_size: { '>': min_file_size } };
	}

	ae_promises.load__event_file_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_file',
			for_obj_type: 'event',
			for_obj_id: event_id,
			use_alt_table: true, // NOTE: We want to use the alt table for file searching?
			use_alt_base: 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_file_obj_li_get_result) {
			if (event_file_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__event_file_props({
						obj_li: event_file_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: 'file',
						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_file({obj_type: 'event_file', obj_li: event_file_obj_li_get_result});
				}
				return event_file_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_file_obj_li:', ae_promises.load__event_file_obj_li);
	}
	return ae_promises.load__event_file_obj_li;
}

// Updated 2025-05-23
export const properties_to_save = [
	'id',
	// 'id_random',
	'event_file_id',
	// 'event_file_id_random',

	'hosted_file_id',
	// 'hosted_file_id_random',
	'hash_sha256',

	'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_presenter_id',
	// 'event_presenter_id_random',
	'event_location_id',
	// 'event_location_id_random',

	'filename',
	'extension',

	'open_in_os',

	'lu_file_purpose_id',
	'lu_event_file_purpose_name',
	'file_purpose',

	'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',

	'filename_no_ext',
	'filename_w_ext',
	'hosted_file_content_type',
	'file_size',
	'hosted_file_size',

	'event_location_code',
	'event_location_name',
	'event_session_code',
	'event_session_type_code',
	'event_session_name',
	'event_session_start_datetime',
	'event_session_end_datetime',
	'event_presentation_code',
	'event_presentation_type_code',
	'event_presentation_name',
	'event_presentation_start_datetime',
	'event_presentation_end_datetime',
	'event_presenter_given_name',
	'event_presenter_family_name',
	'event_presenter_full_name',
	'event_presenter_email'
];

/**
 * 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_file_props({
	obj_li,
	log_lvl = 0
}: {
	obj_li: any[];
	log_lvl?: number;
}) {
	return _process_generic_props({
		obj_li,
		obj_type: 'event_file',
		log_lvl,
		specific_processor: (obj) => {
			// Event file-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;
		}
	});
}
