const dbSAPPS = require("../../helpers/db");
require("dotenv").config();
const { Op } = require("sequelize");

module.exports = {
	create,
	getAll,
	option,
	count,
	update,
	delete: _delete,
};

/**
 * Format an array of medicines by appending a modifier field to each company.
 * The modifier field is the full name of the user who last modified the company.
 * @param {Object[]} medicines - The array of medicines to format.
 * @returns {Promise<Object[]>} - The formatted array of medicines.
 */
const formatWithModifier = async (medicines) => {
	return Promise.all(
		medicines.map(async (medicine) => {
			const modifier = await dbSAPPS.User.findOne({
				where: {
					id: medicine.modified_by,
				},
				attributes: ["full_name"],
			});

			return {
				...medicine,
				modifier: modifier?.full_name,
			};
		})
	);
};

/**
 * Retrieves all medicines with their parent medicine title.
 * @param {Object} params - The query parameters.
 * @param {number[]} params.medicinesId - The ids of the medicines to retrieve.
 * @returns {Promise<Object>} - The response object with the medicines and success status.
 */
async function getAll(params) {
	try {
		// filters
		const filterConditions = {};

		let medicines = [];
		medicines = await dbSAPPS.Medicine.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.DosageForm,
					attributes: ["id", "display_name"],
					as: "dosageform",
				},
				{
					model: dbSAPPS.DosageUnit,
					attributes: ["id", "display_name"],
					as: "dosageunit",
				},
				{
					model: dbSAPPS.Manufacturer,
					attributes: ["id", "display_name"],
					as: "manufacture",
				},
			],
		});

		medicines = medicines.map((medicine) => {
			return {
				...medicine.dataValues,
				dosageform_name: medicine.dosageform?.display_name || null,
				dosageunit_name: medicine.dosageunit?.display_name || null,
				manufacture_name: medicine.manufacture?.display_name || null,
			};
		});

		medicines = await formatWithModifier(medicines);

		return {
			medicines,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error?.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Get medicine items with their respective settings.
 * @param {Object} params - An object that contains parameters to filter the medicine items.
 * @param {boolean|string} params.is_parent - A boolean or string indicating whether the medicine items should be parents or not.
 * @returns {Promise<Object>} Resolves with an object that contains the medicine items and a success flag.
 * @example
 * const result = await option({ is_parent: true });
 * console.log(result);
 */
async function option(params) {
	try {
		// filter
		const filterConditions = {};

		let options = [];
		options = await dbSAPPS.Medicine.findAll({
			attributes: ["id", "name", "display_name", "generic_name", "strength", "dosageform_id", "dosageunit_id", "manufacture_id"],
			where: filterConditions,
			order: [["name", "ASC"]],
			include: [
				{
					model: dbSAPPS.DosageForm,
					attributes: ["id", "display_name"],
					as: "dosageform",
				},
				{
					model: dbSAPPS.DosageUnit,
					attributes: ["id", "display_name"],
					as: "dosageunit",
				},
				{
					model: dbSAPPS.Manufacturer,
					attributes: ["id", "display_name"],
					as: "manufacture",
				},
			],
		});

		options = options.map((option) => {
			return {
				...option.dataValues,
				dosageform_name: option.dosageform?.display_name || null,
				dosageunit_name: option.dosageunit?.display_name || null,
				manufacture_name: option.manufacture?.display_name || null,
			};
		});

		return {
			options,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error?.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Count active medicine items
 *
 * @returns {Promise<{
 *   count: number,
 *   success: boolean,
 *   message: string
 * }>}
 */

async function count(params) {
	try {
		// filter
		const filterConditions = {};

		const count = await dbSAPPS.Medicine.count({
			where: filterConditions,
		});

		return {
			count,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error?.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Creates a new medicine item.
 *
 * @param {Object} params - The new medicine item data.
 * @param {string} params.name - The name of the medicine item.
 * @param {string} params.title - The title of the medicine item.
 * @param {number} [params.parent_id] - The ID of the parent medicine item.
 * @param {string} [params.url] - The URL of the medicine item.
 * @param {string} [params.icon] - The icon of the medicine item.
 * @param {string} [params.type=link] - The type of the medicine item (link, group, collapse, separator).
 * @param {boolean} [params.enabled=true] - Whether the medicine item is enabled.
 * @param {number} [params.creation=Date.now()] - The creation timestamp of the medicine item.
 * @param {number} [params.modified=Date.now()] - The last modification timestamp of the medicine item.
 * @param {number} [params.owner=1] - The ID of the user who created the medicine item.
 * @param {number} [params.modified_by=1] - The ID of the user who last modified the medicine item.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the medicine item creation process.
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existing = await dbSAPPS.Medicine.findOne({
			where: {
				display_name: params.display_name,
				dosageform_id: params.dosageform_id,
				dosageunit_id: params.dosageunit_id,
				manufacture_id: params.manufacture_id,
				strength: params.strength,
			},
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		// save
		await dbSAPPS.Medicine.create(params, { transaction });

		await transaction.commit();
		return {
			success: true,
			message: "Saved successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to save, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Updates an existing medicine item.
 *
 * @param {number} id - The ID of the medicine item to update.
 * @param {Object} params - The updated medicine item data.
 * @param {string} [params.name] - The new name of the medicine item.
 * @param {string} [params.title] - The new title of the medicine item.
 * @param {number} [params.parent_id] - The new parent ID of the medicine item.
 * @param {string} [params.url] - The new URL of the medicine item.
 * @param {string} [params.icon] - The new icon of the medicine item.
 * @param {string} [params.type] - The new type of the medicine item (link, group, collapse, separator).
 * @param {boolean} [params.enabled] - Whether the medicine item is enabled or not.
 * @param {number} [params.creation] - The new creation timestamp of the medicine item.
 * @param {number} [params.modified] - The new last modification timestamp of the medicine item.
 * @param {number} [params.owner] - The new ID of the user who created the medicine item.
 * @param {number} [params.modified_by] - The new ID of the user who last modified the medicine item.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the medicine item update process.
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const medicine = await dbSAPPS.Medicine.findByPk(id);
		if (!medicine) return { success: false, message: "ID not found!" };

		// validate existing
		const existing = await dbSAPPS.Medicine.findOne({
			where: {
				display_name: params.display_name,
				dosageform_id: params.dosageform_id,
				dosageunit_id: params.dosageunit_id,
				manufacture_id: params.manufacture_id,
				strength: params.strength,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		// save
		await medicine.update(params, { transaction });

		await transaction.commit();
		return {
			success: true,
			message: "Saved successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to save, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Delete a medicine
 * @param {number} id - the id of the medicine
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const medicine = await dbSAPPS.Medicine.findByPk(id);
		if (!medicine) return { success: false, message: "ID not found!" };

		// delete
		await medicine.destroy({ transaction });

		await transaction.commit();
		return {
			success: true,
			message: "Deleted successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to delete, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}
