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

const ae_promises: key_val = {};

// Updated 2025-10-06
export async function load_ae_obj_id__event_badge({
	api_cfg,
	event_badge_id,
	inc_template = true,
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_badge_id: string;
	inc_template?: boolean;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** load_ae_obj_id__event_badge() *** event_badge_id=${event_badge_id}`);
	}
	const params = {};
	ae_promises.load__event_badge_obj = await api
		.get_ae_obj_id_crud({
			api_cfg,
			obj_type: 'event_badge',
			obj_id: event_badge_id,
			use_alt_table: false,
			use_alt_base: false,
			params,
			log_lvl
		})
		.then(async function (badge_obj_get_result) {
			if (badge_obj_get_result) {
				if (try_cache) {
					const processed_obj_li = await process_ae_obj__event_badge_props({
						obj_li: [badge_obj_get_result],
						log_lvl
					});
					await db_save_ae_obj_li__ae_obj({
						db_instance: db_events,
						table_name: 'badge',
						obj_li: processed_obj_li,
						properties_to_save,
						log_lvl
					});
				}
				return badge_obj_get_result;
			} else {
				if (log_lvl) console.log('No results returned.');
				return null;
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		});

	if (inc_template) {
		// Load the templates for the event badge
		if (log_lvl) {
			console.log(`Need to load the template for the badge now`);
		}
		const load_event_badge_template_obj = load_ae_obj_id__event_badge_template({
			api_cfg: api_cfg,
			event_badge_template_id: ae_promises.load__event_badge_obj?.event_badge_template_id_random,
			log_lvl: log_lvl
		}).then((event_badge_template_obj_li) => {
			if (log_lvl) {
				console.log(`event_badge_template_obj_li = `, event_badge_template_obj_li);
			}
			return event_badge_template_obj_li;
		});

		if (log_lvl) {
			console.log(`event_badge_template_obj = `, load_event_badge_template_obj);
		}
		ae_promises.load__event_session_obj.event_badge_template = load_event_badge_template_obj;
	}

	return ae_promises.load__event_badge_obj;
}

// Updated 2025-10-06
export async function load_ae_obj_li__event_badge({
	api_cfg,
	event_id,
	inc_template = true, // This should probably be false.
	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;
	event_id: string;
	inc_template?: 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_badge() *** event_id=${event_id}`);
	}
	const params_json: key_val = {};
	// ae_promises.load__event_badge_obj_li = await api.get_ae_obj_li_for_obj_id_crud({
	ae_promises.load__event_badge_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg: api_cfg,
			obj_type: 'event_badge',
			for_obj_type: 'event',
			for_obj_id: event_id,
			// use_alt_tbl: false,
			// 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 (badge_obj_li_get_result) {
			if (badge_obj_li_get_result) {
				if (try_cache) {
					const processed_obj_li = await process_ae_obj__event_badge_props({
						obj_li: badge_obj_li_get_result,
						log_lvl
					});
					await db_save_ae_obj_li__ae_obj({
						db_instance: db_events,
						table_name: 'badge',
						obj_li: processed_obj_li,
						properties_to_save,
						log_lvl
					});
				}
				return badge_obj_li_get_result;
			} else {
				return [];
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		});

	if (inc_template) {
		// Load the template for each badge
		if (log_lvl) {
			console.log(`Need to load the template for each badge now`);
		}
		for (const badge_obj of ae_promises.load__event_badge_obj_li) {
			if (log_lvl) {
				console.log(`Loading template for badge_obj: `, badge_obj);
			}
			const load_event_badge_template_obj = await load_ae_obj_id__event_badge_template({
				api_cfg: api_cfg,
				event_badge_template_id: badge_obj?.event_badge_template_id_random,
				log_lvl: log_lvl
			});
			if (log_lvl) {
				console.log(`event_badge_template_obj = `, load_event_badge_template_obj);
			}
			badge_obj.event_badge_template = load_event_badge_template_obj;
		}
	}

	return ae_promises.load__event_badge_obj_li;
}

// Updated 2025-10-06
export async function create_ae_obj__event_badge({
	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_badge() *** event_id=${event_id}`);
	}
	ae_promises.create__event_badge = await api
		.create_ae_obj_crud({
			api_cfg,
			obj_type: 'event_badge',
			fields: {
				event_id_random: event_id,
				...data_kv
			},
			key: api_cfg.api_crud_super_key,
			params,
			return_obj: true,
			log_lvl
		})
		.then(async function (event_badge_obj_create_result) {
			if (event_badge_obj_create_result) {
				if (try_cache) {
					const processed_obj_li = await process_ae_obj__event_badge_props({
						obj_li: [event_badge_obj_create_result],
						log_lvl
					});
					db_save_ae_obj_li__ae_obj({
						db_instance: db_events,
						table_name: 'badge',
						obj_li: processed_obj_li,
						properties_to_save,
						log_lvl
					});
				}
				return event_badge_obj_create_result;
			} else {
				return null;
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		});
	return ae_promises.create__event_badge;
}

// Updated 2025-10-06
export async function delete_ae_obj_id__event_badge({
	api_cfg,
	event_badge_id,
	method = 'delete',
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_badge_id: string;
	method?: string;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** delete_ae_obj_id__event_badge() *** event_badge_id=${event_badge_id}`);
	}
	ae_promises.delete__event_badge_obj = await api
		.delete_ae_obj_id_crud({
			api_cfg,
			obj_type: 'event_badge',
			obj_id: event_badge_id,
			key: api_cfg.api_crud_super_key,
			params,
			method,
			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_badge_id=${event_badge_id}`);
				}
				db_events.badge.delete(event_badge_id);
			}
		});
	return ae_promises.delete__event_badge_obj;
}

// Updated 2025-10-06
export async function update_ae_obj__event_badge({
	api_cfg,
	event_badge_id,
	data_kv,
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	event_badge_id: string;
	data_kv: key_val;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** update_ae_obj__event_badge() *** event_badge_id=${event_badge_id}`);
	}
	ae_promises.update__event_badge_obj = await api
		.update_ae_obj_id_crud({
			api_cfg,
			obj_type: 'event_badge',
			obj_id: event_badge_id,
			fields: data_kv,
			key: api_cfg.api_crud_super_key,
			params,
			return_obj: true,
			log_lvl
		})
		.then(async function (event_badge_obj_update_result) {
			if (event_badge_obj_update_result) {
				if (try_cache) {
					const processed_obj_li = await process_ae_obj__event_badge_props({
						obj_li: [event_badge_obj_update_result],
						log_lvl
					});
					db_save_ae_obj_li__ae_obj({
						db_instance: db_events,
						table_name: 'badge',
						obj_li: processed_obj_li,
						properties_to_save,
						log_lvl
					});
				}
				return event_badge_obj_update_result;
			} else {
				return null;
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		});
	return ae_promises.update__event_badge_obj;
}

// Is this needed?
// Updated 2025-10-06
export async function qry__event_badge({
	api_cfg,
	event_id,
	qry_str = null,
	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;
	event_id: string;
	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?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** qry__event_badge() *** event_id=${event_id}`);
	}
	const params_json: key_val = {};
	if (qry_str) {
		params_json['ft_qry'] = { default_qry_str: qry_str };
	}
	ae_promises.qry__event_badge_obj_li = await load_ae_obj_li__event_badge({
		api_cfg,
		event_id,
		enabled,
		hidden,
		limit,
		offset,
		order_by_li,
		params: { ...params, ...params_json },
		try_cache,
		log_lvl
	});
	return ae_promises.qry__event_badge_obj_li;
}

// Updated 2025-10-06
export async function search__event_badge({
	api_cfg,
	event_id,
	type_code = null,
	fulltext_search_qry_str,
	like_search_qry_str = null,
	external_event_id,
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 25,
	offset = 0,
	order_by_li = {
		print_count: 'ASC',
		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;
	event_id: string;
	type_code?: null | string;
	external_event_id?: null | string;
	fulltext_search_qry_str?: null | string;
	like_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?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** search__event_badge() *** event_id=${event_id}`);
	}

	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.
	}

	const params_json: key_val = {};
	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
	}
	if (like_search_qry_str && like_search_qry_str.length > 2) {
		// Old Python version that needs to be in JS
		// # Strip (left right) whitespace then commas then semicolons
		// query_str = query_str.strip().strip(',').strip(';')
		//  # Replace commas, semicolons, and then spaces with %
		// query_str_like = query_str.replace(',', ' ').replace(';', ' ').replace('  ', '%').replace(' ', '%')
		// # data['query_str'] = f'%{query_str}%'
		// log.debug(query_str_like)
		// data['query_str'] = f'%{query_str_like}%'

		// let like_search_qry_str_new = like_search_qry_str.trim().replace(',', ' ').replace(';', ' ').replace('  ', '%').replace(' ', '%');
		// like_search_qry_str_new = `%${like_search_qry_str_new}%`;
		// console.log('like_search_qry_str_new:', like_search_qry_str_new);

		params_json['and_like'] = { default_qry_str: like_search_qry_str };
	}

	params_json['and_qry'] = {};
	if (external_event_id) {
		params_json['and_qry']['external_event_id'] = external_event_id;
	}
	if (type_code) {
		// This is the event_badge.badge_type_code. There is also a member_type_code and registration_type_code that could be referenced in the future.
		params_json['and_qry']['badge_type_code'] = type_code;
	}

	// ae_promises.search__event_badge_obj_li = await api.get_ae_obj_li_for_obj_id_crud({
	ae_promises.search__event_badge_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg,
			obj_type: 'event_badge',
			for_obj_type: 'event',
			for_obj_id: event_id,
			use_alt_tbl: false,
			use_alt_mdl: true,
			enabled,
			hidden,
			order_by_li,
			limit,
			offset,
			params_json,
			params,
			log_lvl
		})
		.then(async function (badge_obj_li_get_result) {
			if (badge_obj_li_get_result) {
				if (try_cache) {
					const processed_obj_li = await process_ae_obj__event_badge_props({
						obj_li: badge_obj_li_get_result,
						log_lvl
					});
					await db_save_ae_obj_li__ae_obj({
						db_instance: db_events,
						table_name: 'badge',
						obj_li: processed_obj_li,
						properties_to_save,
						log_lvl
					});
				}
				return badge_obj_li_get_result;
			} else {
				return [];
			}
		})
		.catch(function (error: any) {
			console.log('No results returned or failed.', error);
		});
	return ae_promises.search__event_badge_obj_li;
}

// Updated 2025-10-06
export const properties_to_save = [
	'id',
	'event_badge_id',
	// 'event_badge_id_random',

	'event_id',
	// 'event_id_random',

	'event_badge_template_id',
	// 'event_badge_template_id_random',

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

	'professional_title',
	'professional_title_override',

	'full_name',
	'full_name_override',

	'affiliations',
	'affiliations_override',

	'email',
	'email_override',

	'address_line_1',
	'address_line_2',
	'address_line_3',
	'city',
	'country_subdivision_code',
	'state_province',
	'state_province_abb',
	'postal_code',
	'country_alpha_2_code',
	'country',
	'full_address',
	'location',
	'location_override',

	'query_str',

	'badge_type',
	'badge_type_code',
	'badge_type_override',
	'badge_type_code_override',
	'external_event_id',
	'external_id',
	'external_person_id',

	'default_qry_string',

	'alert',

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

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

	'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-10-06
export async function process_ae_obj__event_badge_props({
	obj_li,
	log_lvl = 0
}: {
	obj_li: any[];
	log_lvl?: number;
}) {
	return _process_generic_props({
		obj_li,
		obj_type: 'event_badge',
		log_lvl,
		specific_processor: (obj) => {
			// Event badge-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.print_count ?? '0'}_${obj.priority ? '1' : '0'}_${
				obj.sort?.toString().padStart(3, '0') ?? ''
			}_${obj.given_name ?? ''}_${obj.family_name ?? ''}_${obj.updated_on ?? obj.created_on}`;

			return obj;
		}
	});
}
