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

import { db_events } from '$lib/ae_events/db_events';

// --- PROPERTIES TO SAVE ---
export const properties_to_save_exhibit_tracking = [
	'id',
	'event_exhibit_tracking_id',
	'event_exhibit_id',
	'event_badge_id',
	'event_person_id',
	'external_person_id',
	'exhibitor_notes',
	'responses_json',
	'data_json',
	'event_exhibit_name',
	'event_badge_title_names',
	'event_badge_given_name',
	'event_badge_family_name',
	'event_badge_designations',
	'event_badge_full_name',
	'event_badge_full_name_override',
	'event_badge_professional_title',
	'event_badge_professional_title_override',
	'event_badge_affiliations',
	'event_badge_affiliations_override',
	'event_badge_email',
	'event_badge_email_override',
	'event_badge_location',
	'event_badge_location_override',
	'event_badge_country',
	'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__exhibit_tracking_props({
	obj_li,
	log_lvl = 0
}: {
	obj_li: any[];
	log_lvl?: number;
}) {
	return _process_generic_props({
		obj_li,
		obj_type: 'event_exhibit_tracking',
		log_lvl,
		specific_processor: (obj) => {
			// Event exhibit tracking-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;
		}
	});
}

// --- PROPERTIES TO SAVE ---
export const properties_to_save = [
	'id',
	'event_exhibit_id',
	'event_id',
	'code',
	'name',
	'description',
	'staff_passcode',
	'data_json',
	'leads_api_access',
	'leads_custom_questions_json',
	'leads_device_sm_qty',
	'leads_device_lg_qty',
	'license_max',
	'license_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'
];

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

// --- PROCESS FUNCTION ---
export async function process_ae_obj__exhibit_props({
	obj_li,
	log_lvl = 0
}: {
	obj_li: any[];
	log_lvl?: number;
}) {
	return _process_generic_props({
		obj_li,
		obj_type: 'event_exhibit',
		log_lvl,
		specific_processor: (obj) => {
			// Event exhibit-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;
		}
	});
}

// Updated 2024-03
export async function load_ae_obj_id__exhibit({
	api_cfg,
	exhibit_id,
	try_cache = false,
	log_lvl = 0
}: {
	api_cfg: any;
	exhibit_id: string;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	console.log(`*** load_ae_obj_id__exhibit() *** exhibit_id=${exhibit_id}`);

	const params = {};

	// $events_sess.exhibits.status_load__exhibit_obj = 'loading';
	ae_promises.load__exhibit_obj = await api
		.get_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_exhibit',
			obj_id: exhibit_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 in the API config.
			params: params,
			log_lvl: log_lvl
		})
		.then(async function (exhibit_obj_get_result) {
			if (exhibit_obj_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__exhibit_props({
						obj_li: [exhibit_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: 'exhibit',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}
				}
				return exhibit_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__exhibit_obj;
}

// Updated 2024-03-06
export async function load_ae_obj_li__exhibit({
	api_cfg,
	event_id,
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_id: any;
	params: any;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	console.log(`*** load_ae_obj_li__exhibit() *** 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 ?? 99; // 99
	const offset: number = params.qry__offset ?? 0; // 0

	const params_json: key_val = {};
	// params_json['and_qry'] = {};
	// params_json['and_qry']['license_max'] = 10;

	params_json['and_in_li'] = {
		license_max: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
	};

	// if (fulltext_search_qry_str && fulltext_search_qry_str.length > 2) {
	//     params_json['ft_qry'] = {
	//         'default_qry_str': fulltext_search_qry_str,
	//         // 'location_address_json_ext': fulltext_search_qry_str, // JSON extracted text DB field
	//         // 'contact_li_json_ext': fulltext_search_qry_str, // JSON extracted text DB field
	//         };
	// }

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

	// $events_sess.exhibits.status_qry__search = 'loading';
	ae_promises.load__event_exhibit_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_exhibit',
			for_obj_type: 'event',
			for_obj_id: event_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 in the API config.
			enabled: enabled,
			hidden: hidden,
			order_by_li: { priority: 'DESC', sort: 'DESC', updated_on: 'DESC', created_on: 'DESC' },
			// order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'created_on': 'DESC', 'updated_on': 'DESC'},
			limit: limit,
			offset: offset,
			params_json: params_json,
			params: params,
			log_lvl: log_lvl
		})

		.then(async function (exhibit_obj_li_get_result) {
			// console.log('Badge list:', exhibit_obj_li_get_result);
			if (exhibit_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__exhibit_props({
						obj_li: exhibit_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: 'exhibit',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}
				}
				return exhibit_obj_li_get_result;
			} else {
				// $slct.exhibit_obj_li = [];
				return [];
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		})
		.finally(function () {
			// $events_sess.exhibits.status_qry__search = 'done';
			// console.log('Badge list:', exhibit_obj_li_get_result);
			// return exhibit_obj_li_get_result;
		});

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

export async function load_ae_obj_id__exhibit_tracking({
	api_cfg,
	exhibit_tracking_id,
	try_cache = false,
	log_lvl = 0
}: {
	api_cfg: any;
	exhibit_tracking_id: string;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	console.log(
		`*** load_ae_obj_id__exhibit_tracking() *** exhibit_tracking_id=${exhibit_tracking_id}`
	);

	const params = {};

	// $events_sess.exhibits.status_load__exhibit_tracking_obj = 'loading';
	ae_promises.load__event_exhibit_tracking_obj = await api
		.get_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_exhibit_tracking',
			obj_id: exhibit_tracking_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 in the API config.
			params: params,
			log_lvl: log_lvl
		})
		.then(async function (exhibit_tracking_obj_get_result) {
			if (exhibit_tracking_obj_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__exhibit_tracking_props({
						obj_li: [exhibit_tracking_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: 'exhibit_tracking',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save_exhibit_tracking,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}
				}
				return exhibit_tracking_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_exhibit_tracking_obj;
}

// Updated 2024-03-19
export async function load_ae_obj_li__exhibit_tracking({
	api_cfg,
	exhibit_id,
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	exhibit_id: any;
	params: any;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	console.log(`*** load_ae_obj_li__exhibit_tracking() *** exhibit_id=${exhibit_id}`);

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

	const params_json: key_val = {};

	ae_promises.load__event_exhibit_tracking_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_exhibit_tracking',
			for_obj_type: 'event_exhibit',
			for_obj_id: exhibit_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 in the API config.
			enabled: enabled,
			hidden: hidden,
			order_by_li: { priority: 'DESC', sort: 'DESC', updated_on: 'DESC', created_on: 'DESC' },
			limit: limit,
			offset: offset,
			params_json: params_json,
			params: params,
			log_lvl: log_lvl
		})

		.then(async function (exhibit_tracking_obj_li_get_result) {
			// console.log('Exhibit tracking list:', exhibit_tracking_obj_li_get_result);
			if (exhibit_tracking_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__exhibit_tracking_props({
						obj_li: exhibit_tracking_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: 'exhibit_tracking',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save_exhibit_tracking,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}
				}
				return exhibit_tracking_obj_li_get_result;
			} else {
				// $slct.exhibit_tracking_obj_li = [];
				return [];
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		})
		.finally(function () {
			// console.log('Exhibit tracking list:', exhibit_tracking_obj_li_get_result);
			// return exhibit_tracking_obj_li_get_result;
		});

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

// Updated 2024-03-22
export async function create_ae_obj__exhibit_tracking({
	api_cfg,
	exhibit_id,
	event_badge_id,
	external_person_id,
	params = {},
	log_lvl = 0
}: {
	api_cfg: any;
	exhibit_id: string;
	event_badge_id: string;
	external_person_id: string;
	params: key_val;
	log_lvl: number;
}) {
	console.log(
		`*** handle_create_ae_obj__exhibit_tracking() *** exhibit_id=${exhibit_id}, event_badge_id=${event_badge_id}`
	);

	const params_json: key_val = {};

	// $events_sess.exhibits.status_create__exhibit_tracking = 'loading';
	ae_promises.create__event_exhibit_tracking = await api
		.create_ae_obj_crud({
			api_cfg: api_cfg,
			obj_type: 'event_exhibit_tracking',
			fields: {
				event_exhibit_id_random: exhibit_id,
				event_badge_id_random: event_badge_id,
				external_person_id: external_person_id
			},
			key: api_cfg.api_crud_super_key,
			params: params,
			return_obj: true,
			log_lvl: log_lvl
		})

		.then(async function (exhibit_tracking_obj_create_result) {
			// console.log('Exhibit tracking create:', exhibit_tracking_obj_create_result);
			if (exhibit_tracking_obj_create_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__exhibit_tracking_props({
						obj_li: [exhibit_tracking_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: 'exhibit_tracking',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save_exhibit_tracking,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}
				}
				return exhibit_tracking_obj_create_result;
			} else {
				// $slct.exhibit_tracking_obj = [];
				return null;
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		})
		.finally(function () {
			// console.log('Exhibit tracking create:', exhibit_tracking_obj_create_result);
			// return exhibit_tracking_obj_create_result;
		});

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

// Updated 2024-03-28
export async function update_ae_obj__exhibit_tracking({
	api_cfg,
	exhibit_tracking_id,
	data,
	params = {},
	log_lvl = 0
}: {
	api_cfg: any;
	exhibit_tracking_id: string;
	data: any;
	params: key_val;
	log_lvl: number;
}) {
	console.log(
		`*** handle_update_ae_obj__exhibit_tracking() *** exhibit_tracking_id=${exhibit_tracking_id}`
	);

	ae_promises.update__event_exhibit_tracking = await api
		.update_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'event_exhibit_tracking',
			obj_id: exhibit_tracking_id,
			fields: data,
			key: api_cfg.api_crud_super_key,
			params: params,
			return_obj: true,
			log_lvl: log_lvl
		})
		.then(async function (exhibit_tracking_obj_update_result) {
			if (exhibit_tracking_obj_update_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__exhibit_tracking_props({
						obj_li: [exhibit_tracking_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: 'exhibit_tracking',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save_exhibit_tracking,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}
				}
				return exhibit_tracking_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_exhibit_tracking:',
			ae_promises.update__event_exhibit_tracking
		);
	}
	return ae_promises.update__event_exhibit_tracking;
}

export async function download_export__event_exhibit_tracking({
	api_cfg,
	exhibit_id,
	file_type = 'CSV', // 'CSV' or 'Excel'
	return_file = true,
	filename = 'no_filename.csv',
	auto_download = false,
	params = {},
	log_lvl = 0
}: {
	api_cfg: any;
	exhibit_id: string;
	file_type?: string;
	return_file?: boolean;
	filename?: string;
	auto_download?: boolean;
	params?: key_val;
	log_lvl?: number;
}) {
	console.log('*** ae_events_functions.js: get_event_exhibit_tracking_export() ***');

	const endpoint = `/event/exhibit/${exhibit_id}/tracking/export`;
	if (file_type == 'CSV' || file_type == 'Excel') {
		params['file_type'] = file_type;
	}
	params['return_file'] = true;

	ae_promises.download__event_exhibit_tracking_export_file = await api.get_object({
		api_cfg: api_cfg,
		endpoint: endpoint,
		params: params,
		return_blob: true,
		filename: filename,
		auto_download: auto_download,
		log_lvl: log_lvl
	});

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