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

import { db_core } from '$lib/ae_core/db_core';

const ae_promises: key_val = {};

// Updated 2025-04-04
export async function auth_ae_obj__username_password({
	api_cfg,
	account_id,
	null_account_id = false,
	username,
	password,
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	account_id: string;
	null_account_id?: boolean;
	username: string;
	password: string;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** auth_ae_obj__username_password() *** account_id=${account_id} username=${username} password=${password}`
		);
	}

	const endpoint = '/user/authenticate';

	if (null_account_id) {
		params['null_account_id'] = true;
	}
	params['username'] = username; // Required
	params['password'] = password; // Required
	if (log_lvl > 1) {
		console.log(`auth_ae_obj__username_password() - params:`, params);
	}

	ae_promises.auth__username_password = await api
		.get_object({
			api_cfg: api_cfg,
			endpoint: endpoint,
			params: params,
			// data: {},
			log_lvl: log_lvl
		})
		.then(async function (user_obj_get_result) {
			if (user_obj_get_result) {
				// if (try_cache) {
				//     // This is expecting a list
				//     db_save_ae_obj_li__user({
				//         obj_type: 'user',
				//         obj_li: [user_obj_get_result],
				//         log_lvl: log_lvl
				//     });
				// }
				return user_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.auth__username_password:', ae_promises.auth__username_password);
	}
	return ae_promises.auth__username_password;
}

// Updated 2025-04-04
export async function auth_ae_obj__user_id_user_auth_key({
	api_cfg,
	account_id,
	user_id,
	user_auth_key,
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	account_id: string;
	user_id: string;
	user_auth_key: string;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** auth_ae_obj__user_id_user_auth_key() *** account_id=${account_id} user_id=${user_id}`
		);
	}

	const endpoint = '/user/authenticate';

	params['user_id'] = user_id; // Required
	params['auth_key'] = user_auth_key; // Required
	if (log_lvl > 1) {
		console.log(`auth_ae_obj__user_id_user_auth_key() - params:`, params);
	}

	ae_promises.auth__user_id_user_key = await api
		.get_object({
			api_cfg: api_cfg,
			endpoint: endpoint,
			params: params,
			log_lvl: log_lvl
		})
		.then(async function (user_obj_get_result) {
			if (user_obj_get_result) {
				return user_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.auth__user_id_user_key:', ae_promises.auth__user_id_user_key);
	}
	return ae_promises.auth__user_id_user_key;
}

// Send an email to the user with a new one time use authentication key. The new key must be generated and returned first.
// Updated 2025-04-08
export async function send_email_auth_ae_obj__user_id({
	api_cfg,
	account_id,
	user_id,
	base_url,
	key_param_name = 'user_key', // API defaults to 'auth_key'
	params = {},
	// try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	account_id: string;
	user_id: string;
	base_url?: string;
	key_param_name?: string;
	params?: key_val;
	// try_cache?: boolean,
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** send_email_auth_ae_obj__user_id() *** account_id=${account_id} user_id=${user_id}`
		);
	}
	if (log_lvl > 1) {
		console.log(api_cfg);
	}

	const email_auth_key_endpoint = `user/${user_id}/email_auth_key_url`;
	params = {
		root_url: base_url,
		key_param_name: key_param_name
	};
	ae_promises.auth_key__send_email = await api.get_object({
		api_cfg: api_cfg,
		endpoint: email_auth_key_endpoint,
		params: params,
		log_lvl: log_lvl
	});

	return ae_promises.auth_key__send_email;

	// let endpoint = `/user/${user_id}/new_auth_key`;

	// // params['user_id'] = user_id; // Required
	// if (log_lvl > 1) {
	//     console.log(`send_email_auth_ae_obj__user_id() - params:`, params);
	// }

	// ae_promises.auth_key__gen_auth_key = await api.get_object({
	//     api_cfg: api_cfg,
	//     endpoint: endpoint,
	//     params: params,
	//     log_lvl: log_lvl
	//     })
	// .then(async function (email_send_result) {
	//     if (email_send_result) {
	//         let email_auth_key_endpoint = `user/${user_id}/email_auth_key_url`;
	//         params = {
	//             'root_url': 'https://test.oneskyit.com'
	//         }
	//         ae_promises.auth_key__send_email = await api.get_object({
	//             api_cfg: api_cfg,
	//             endpoint: email_auth_key_endpoint,
	//             params: params,
	//             log_lvl: log_lvl
	//         })

	//         return email_send_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.send_email_auth__user_id:', ae_promises.send_email_auth__user_id);
	// }
	// return ae_promises.send_email_auth__user_id;
}

// Look up user based on email address provided
// Updated 2025-04-08
export async function qry_ae_obj_li__user_email({
	api_cfg,
	account_id,
	null_account_id = false,
	email,
	params = {},
	try_cache = true,
	log_lvl = 0
}: {
	api_cfg: any;
	account_id: string;
	null_account_id?: boolean;
	email: string;
	params?: key_val;
	try_cache?: boolean;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(`*** qry_ae_obj_li__user_email() *** account_id=${account_id} email=${email}`);
	}

	const endpoint = '/user/lookup_email';

	params['email'] = email; // Required
	params['null_account_id'] = null_account_id || false;
	if (log_lvl > 1) {
		console.log(`qry_ae_obj_li__user_email() - params:`, params);
	}

	ae_promises.qry__user_email = await api
		.get_object({
			api_cfg: api_cfg,
			endpoint: endpoint,
			params: params,
			log_lvl: log_lvl
		})
		.then(async function (user_obj_get_result) {
			if (user_obj_get_result) {
				return user_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.qry__user_email:', ae_promises.qry__user_email);
	}
	return ae_promises.qry__user_email;
}

// Change user password
// endpoint: PATCH /user/{user_id}/change_password
// params:
// data_kv: password (the new password)
// Updated 2025-04-11
export async function auth_ae_obj__user_id_change_password({
	api_cfg,
	account_id,
	user_id,
	password,
	params = {},
	log_lvl = 0
}: {
	api_cfg: any;
	account_id: string;
	user_id: string;
	password: string;
	params?: key_val;
	log_lvl?: number;
}) {
	if (log_lvl) {
		console.log(
			`*** auth_ae_obj__user_id_change_password() *** account_id=${account_id} user_id=${user_id}`
		);
	}

	const endpoint = `/user/${user_id}/change_password`;

	params['user_id'] = user_id; // Required
	if (log_lvl > 1) {
		console.log(`auth_ae_obj__user_id_change_password() - params:`, params);
	}

	ae_promises.change_password__user_id = await api
		.patch_object({
			api_cfg: api_cfg,
			endpoint: endpoint,
			params: params,
			data: { password: password },
			log_lvl: log_lvl
		})
		.then(async function (change_password_result) {
			if (change_password_result) {
				return change_password_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.change_password__user_id:', ae_promises.change_password__user_id);
	}
	return ae_promises.change_password__user_id;
}
