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

const ae_promises: key_val = {};

// Updated 2024-10-23
export async function load_ae_obj_id__activity_log({
	api_cfg,
	activity_log_id,
	// inc_other_li = false,
	try_cache = false,
	log_lvl = 0
}: {
	api_cfg: any;
	activity_log_id: string;
	// inc_other_li?: boolean,
	try_cache?: boolean;
	log_lvl?: number;
}) {
	console.log(`*** load_ae_obj_id__activity_log() *** activity_log_id=${activity_log_id}`);

	const params = {};

	ae_promises.load__activity_log_obj = await api
		.get_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'activity_log',
			obj_id: activity_log_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(function (activity_log_obj_get_result) {
			if (activity_log_obj_get_result) {
				// if (try_cache) {
				//     // This is expecting a list
				//     db_save_ae_obj_li__activity_log({
				//         obj_type: 'activity_log',
				//         obj_li: [activity_log_obj_get_result]
				//     });
				// }
				return activity_log_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__activity_log_obj:', ae_promises.load__activity_log_obj);
	}

	return ae_promises.load__activity_log_obj;
}

// Updated 2024-10-23
export async function load_ae_obj_li__activity_log({
	api_cfg,
	for_obj_type = 'account',
	for_obj_id,
	// inc_other_li = false,
	order_by_li = {
		priority: 'DESC',
		sort: 'DESC',
		name: 'ASC',
		updated_on: 'DESC',
		created_on: 'DESC'
	},
	params = {},
	try_cache = false,
	log_lvl = 0
}: {
	api_cfg: any;
	for_obj_type: string;
	for_obj_id: string;
	// inc_other_li?: boolean,
	order_by_li?: key_val;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	console.log(
		`*** load_ae_obj_li__activity_log() *** for_obj_type=${for_obj_type} for_obj_id=${for_obj_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 = {};

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

	ae_promises.load__activity_log_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'activity_log',
			for_obj_type: for_obj_type,
			for_obj_id: for_obj_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
			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 (activity_log_obj_li_get_result) {
			if (activity_log_obj_li_get_result) {
				// if (try_cache) {
				//     db_save_ae_obj_li__activity_log({
				//         obj_type: 'activity_log',
				//         obj_li: activity_log_obj_li_get_result
				//     });
				// }
				return activity_log_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__activity_log_obj_li:', ae_promises.load__activity_log_obj_li);
	}

	return ae_promises.load__activity_log_obj_li;
}

// Updated 2024-10-23
export async function create_ae_obj__activity_log({
	api_cfg,
	account_id,
	data_kv,
	params = {},
	log_lvl = 0
}: {
	api_cfg: any;
	account_id: string;
	data_kv: key_val;
	params?: key_val;
	log_lvl?: number;
}) {
	console.log(`*** create_ae_obj__activity_log() *** account_id=${account_id}`);

	ae_promises.create__activity_log = await api
		.create_ae_obj_crud({
			api_cfg: api_cfg,
			obj_type: 'activity_log',
			fields: {
				account_id_random: account_id,
				...data_kv
			},
			key: api_cfg.api_crud_super_key,
			params: params,
			return_obj: true,
			log_lvl: log_lvl
		})
		.then(function (activity_log_obj_create_result) {
			if (activity_log_obj_create_result) {
				// db_save_ae_obj_li__activity_log(
				//     {
				//         obj_type: 'activity_log',
				//         obj_li: [activity_log_obj_create_result]
				//     });
				return activity_log_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__activity_log:', ae_promises.create__activity_log);
	}
	return ae_promises.create__activity_log;
}

// Updated 2024-10-23
export async function update_ae_obj__activity_log({
	api_cfg,
	activity_log_id,
	data_kv,
	params = {},
	try_cache = false,
	log_lvl = 0
}: {
	api_cfg: any;
	activity_log_id: string;
	data_kv: key_val;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** update_ae_obj__activity_log() *** activity_log_id=${activity_log_id}`,
			data_kv
		);
	}
	ae_promises.update__activity_log_obj = await api
		.update_ae_obj_id_crud({
			api_cfg: api_cfg,
			obj_type: 'activity_log',
			obj_id: activity_log_id,
			fields: data_kv,
			key: api_cfg.api_crud_super_key,
			params: params,
			return_obj: true,
			log_lvl: log_lvl
		})
		.then(function (activity_log_obj_update_result) {
			if (activity_log_obj_update_result) {
				// if (try_cache) {
				//     db_save_ae_obj_li__activity_log({
				//         obj_type: 'activity_log', obj_li: [activity_log_obj_update_result]
				//     });
				// }
				return activity_log_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__activity_log_obj:', ae_promises.update__activity_log_obj);
	}
	return ae_promises.update__activity_log_obj;
}

// This new function is using CRUD v2. This should allow for more flexibility in the queries.
// Updated 2024-10-23
export async function qry__activity_log({
	api_cfg,
	activity_log_id,
	qry_str,
	qry_files,
	qry_start_datetime, // Example greater than: '2024-10-24'
	enabled = 'enabled',
	hidden = 'not_hidden',
	limit = 50,
	offset = 0,
	params = {},
	try_cache = false,
	log_lvl = 0
}: {
	api_cfg: any;
	activity_log_id: any;
	qry_str?: string;
	qry_files?: null | boolean;
	qry_start_datetime?: null | string; // Greater than this datetime
	enabled?: 'enabled' | 'all' | 'not_enabled' | undefined; // all, disabled, enabled
	hidden?: 'hidden' | 'all' | 'not_hidden' | undefined; // all, hidden, not_hidden
	limit?: number;
	offset?: number;
	params?: any;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	console.log(`*** qry__activity_log() *** activity_log_id=${activity_log_id} qry_str=${qry_str}`);

	// 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 (qry_str && qry_str.length > 2) {
	//     params_json['ft_qry'] = {};
	//     params_json['ft_qry']['default_qry_str'] = qry_str;
	// }

	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);
	}

	const order_by_li: { [key: string]: 'ASC' | 'DESC' }[] = [
		{ priority: 'DESC' },
		{ sort: 'DESC' },
		{ start_datetime: 'ASC' },
		{ name: 'ASC' },
		{ updated_on: 'DESC' },
		{ created_on: 'DESC' }
	];

	ae_promises.load__activity_log_obj_li = await api
		.get_ae_obj_li_for_obj_id_crud_v2({
			api_cfg: api_cfg,
			obj_type: 'activity_log',
			for_obj_type: 'account',
			for_obj_id: activity_log_id,
			use_alt_tbl: true, // NOTE: We want to use the alt table for activity_log 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 (activity_log_obj_li_get_result) {
			if (activity_log_obj_li_get_result) {
				// db_save_ae_obj_li__activity_log({
				//     obj_type: 'activity_log',
				//     obj_li: activity_log_obj_li_get_result
				// });
				return activity_log_obj_li_get_result;
			} else {
				return [];
			}
		});

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