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

import { db_sponsorships } from '$lib/ae_sponsorships/db_sponsorships';

// import { liveQuery } from "dexie";
// import { db_core } from "$lib/db_core";

// --- PROPERTIES TO SAVE ---
export const properties_to_save_sponsorship_cfg = [
	'id',
	'sponsorship_cfg_id',
	'account_id',
	'for_type',
	'for_id',
	'level_li_json',
	'option_li_json',
	'schedule_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'
];

// --- PROCESS FUNCTION ---
export async function process_ae_obj__sponsorship_cfg_props({
	obj_li,
	log_lvl = 0
}: {
	obj_li: any[];
	log_lvl?: number;
}) {
	return _process_generic_props({
		obj_li,
		obj_type: 'sponsorship_cfg',
		log_lvl,
		specific_processor: (obj) => {
			// Sponsorship Cfg-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_sponsorship = [
	'id',
	'sponsorship_id',
	'account_id',
	'organization_id',
	'person_id',
	'poc_person_id',
	'poc_json',
	'name',
	'name_override',
	'description',
	'email',
	'website_url',
	'logo_li_json',
	'media_li_json',
	'social_li_json',
	'address_li_json',
	'contact_li_json',
	'guest_li_json',
	'level_num',
	'level_str',
	'amount',
	'questions_li_json',
	'agree',
	'comments',
	'staff_notes',
	'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__sponsorship_props({
	obj_li,
	log_lvl = 0
}: {
	obj_li: any[];
	log_lvl?: number;
}) {
	return _process_generic_props({
		obj_li,
		obj_type: 'sponsorship',
		log_lvl,
		specific_processor: (obj) => {
			// Sponsorship-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;
		}
	});
}

/**
 * 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 2024-03-29
async function load_ae_obj_id__sponsorship_cfg({
	api_cfg,
	sponsorship_cfg_id,
	try_cache = false,
	log_lvl = 0
}: {
	api_cfg: any;
	sponsorship_cfg_id: string;
	try_cache: boolean;
	log_lvl: number;
}) {
	if (log_lvl) {
		console.log(
			`*** load_ae_obj_id__sponsorship_cfg() *** sponsorship_cfg_id=${sponsorship_cfg_id}`
		);
	}

	const params = {};

	ae_promises.load__sponsorship_cfg_obj = api
		.get_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'sponsorship_cfg',
			obj_id: sponsorship_cfg_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 (sponsorship_cfg_obj_get_result) {
			if (sponsorship_cfg_obj_get_result) {
				if (log_lvl) {
					console.log(`*spons_func* Got a result for sponsorship_cfg_id ${sponsorship_cfg_id}`);
				} else if (log_lvl > 1) {
					console.log(
						`*spons_func* Got a result for sponsorship_cfg_id ${sponsorship_cfg_id}:`,
						sponsorship_cfg_obj_get_result
					);
				}
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__sponsorship_cfg_props({
						obj_li: [sponsorship_cfg_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_sponsorships,
						table_name: 'cfg',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save_sponsorship_cfg,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}
				}
				return sponsorship_cfg_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__sponsorship_cfg_obj:', ae_promises.load__sponsorship_cfg_obj);
	}

	return ae_promises.load__sponsorship_cfg_obj;
}

// Updated 2024-03-29
async function load_ae_obj_id__sponsorship({
	api_cfg,
	sponsorship_id,
	try_cache = false,
	log_lvl = 0
}: {
	api_cfg: any;
	sponsorship_id: string;
	try_cache: boolean;
	log_lvl: number;
}) {
	if (log_lvl) {
		console.log(`*** load_ae_obj_id__sponsorship() *** sponsorship_id=${sponsorship_id}`);
	}

	const params = {};

	ae_promises.load__sponsorship_obj = api
		.get_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'sponsorship',
			obj_id: sponsorship_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 (sponsorship_obj_get_result) {
			if (sponsorship_obj_get_result) {
				if (log_lvl) {
					console.log(`*spons_func* Got a result for sponsorship_id ${sponsorship_id}`);
				} else if (log_lvl > 1) {
					console.log(
						`*spons_func* Got a result for sponsorship_id ${sponsorship_id}:`,
						sponsorship_obj_get_result
					);
				}
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__sponsorship_props({
						obj_li: [sponsorship_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_sponsorships,
						table_name: 'sponsorship',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save_sponsorship,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}
				}
				return sponsorship_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__sponsorship_obj:', ae_promises.load__sponsorship_obj);
	}

	return ae_promises.load__sponsorship_obj;
}

// Updated 2025-01-15
async function load_ae_obj_li__sponsorship({
	api_cfg,
	for_obj_type = 'account',
	for_obj_id,
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 99,
	offset = 0,
	order_by_li = {
		priority: 'DESC',
		sort: 'DESC',
		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_content_li?: boolean;
	enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
	hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
	limit?: number;
	offset?: number;
	order_by_li?: key_val;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** load_ae_obj_li__sponsorship() *** for_obj_type=${for_obj_type} for_obj_id=${for_obj_id}`
		);
	}

	const params_json: key_val = {};

	ae_promises.load__sponsorship_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg: api_cfg,
			obj_type: 'sponsorship',
			for_obj_type: for_obj_type,
			for_obj_id: for_obj_id,
			use_alt_tbl: false,
			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 (sponsorship_obj_li_get_result) {
			if (sponsorship_obj_li_get_result) {
				if (try_cache) {
					// Process the results first
					const processed_obj_li = await process_ae_obj__sponsorship_props({
						obj_li: sponsorship_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_sponsorships,
						table_name: 'sponsorship',
						obj_li: processed_obj_li,
						properties_to_save: properties_to_save_sponsorship,
						log_lvl: log_lvl
					});
					if (log_lvl) {
						console.log('DB save completed.');
					}
				}
				return sponsorship_obj_li_get_result;
			} else {
				return [];
			}
		});

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

	return ae_promises.load__sponsorship_obj_li;
}

export async function download_export__sponsorship({
	api_cfg,
	account_id,
	file_type = 'CSV', // 'CSV' or 'Excel'
	return_file = true,
	filename = 'no_filename.csv',
	auto_download = false,
	params = {}, // key value object is expected
	log_lvl = 0
}: {
	api_cfg: any;
	account_id: string;
	file_type?: string;
	return_file?: boolean;
	filename?: string;
	auto_download?: boolean;
	params?: key_val;
	log_lvl?: number;
}) {
	console.log('*** stores_event_api.js: get_sponsorship_export() ***');

	const endpoint = `/v2/crud/sponsorship/list`;
	params['for_obj_type'] = 'account';
	params['for_obj_id'] = account_id;

	if (file_type == 'CSV' || file_type == 'Excel') {
		params['file_type'] = file_type;
	}
	params['return_file'] = true;

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

	console.log(
		'ae_promises.download__sponsorship_export_file:',
		ae_promises.download__sponsorship_export_file
	);
	return ae_promises.download__sponsorship_export_file;
}

const export_obj = {
	load_ae_obj_id__sponsorship_cfg: load_ae_obj_id__sponsorship_cfg,
	load_ae_obj_id__sponsorship: load_ae_obj_id__sponsorship,
	load_ae_obj_li__sponsorship: load_ae_obj_li__sponsorship,
	download_export__sponsorship: download_export__sponsorship
};
export const spons_func = export_obj;
