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 patients 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[]} patients - The array of patients to format.
 * @returns {Promise<Object[]>} - The formatted array of patients.
 */
const formatWithModifier = async (patients) => {
	return Promise.all(
		patients.map(async (patient) => {
			const modifier = await dbSAPPS.User.findOne({
				where: {
					id: patient.modified_by,
				},
				attributes: ["full_name"],
			});

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

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

		if (params.patient_id) {
			filterConditions.id = {
				[Op.eq]: params.patient_id,
			};
		}

		if (params.company_id) {
			filterConditions.company_id = {
				[Op.eq]: params.company_id,
			};
		}

		if (params.companiesId) {
			filterConditions.company_id = {
				[Op.in]: params.companiesId,
			};
		}

		let patients = [];
		patients = await dbSAPPS.Patient.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.User,
					as: "user",
					attributes: ["id", "full_name", "email"],
				},
				{
					model: dbSAPPS.Hospital,
					as: "hospital",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Religion,
					as: "religion",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.BloodGroup,
					as: "bloodgroup",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.MaritalStatus,
					as: "maritalstatus",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Occupation,
					as: "occupation",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Nationality,
					as: "nationality",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Gender,
					as: "gender",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Age,
					as: "agerange",
					attributes: ["id", "name", "display_name"],
				},
			],
		});

		patients = patients.map((patient) => {
			return {
				...patient.dataValues,
				user_full_name: patient.user ? patient.user.dataValues.full_name : null,
				hospital_name: patient.hospital ? patient.hospital.dataValues.display_name : null,
				company_name: patient.company ? patient.company.dataValues.display_name : null,
				religion_name: patient.religion ? patient.religion.dataValues.display_name : null,
				bloodgroup_name: patient.bloodgroup ? patient.bloodgroup.dataValues.display_name : null,
				maritalstatus_name: patient.maritalstatus ? patient.maritalstatus.dataValues.display_name : null,
				occupation_name: patient.occupation ? patient.occupation.dataValues.display_name : null,
				nationality_name: patient.nationality ? patient.nationality.dataValues.display_name : null,
				gender_name: patient.gender ? patient.gender.dataValues.display_name : null,
				agerange_name: patient.agerange ? patient.agerange.dataValues.display_name : null,
			};
		});

		patients = await formatWithModifier(patients);

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

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

		if (params.patient_id) {
			filterConditions.id = {
				[Op.eq]: params.patient_id,
			};
		}

		if (params.company_id) {
			filterConditions.company_id = {
				[Op.eq]: params.company_id,
			};
		}

		if (params.companiesId) {
			filterConditions.company_id = {
				[Op.in]: params.companiesId,
			};
		}

		let options = [];
		options = await dbSAPPS.Patient.findAll({
			attributes: ["id", "full_name"],
			where: filterConditions,
			order: [["full_name", "ASC"]],
			include: [
				{
					model: dbSAPPS.User,
					as: "user",
					attributes: ["id", "full_name", "email"],
				},
				{
					model: dbSAPPS.Hospital,
					as: "hospital",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Religion,
					as: "religion",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.BloodGroup,
					as: "bloodgroup",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.MaritalStatus,
					as: "maritalstatus",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Occupation,
					as: "occupation",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Nationality,
					as: "nationality",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Gender,
					as: "gender",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Age,
					as: "agerange",
					attributes: ["id", "name", "display_name"],
				},
			],
		});

		options = options.map((option) => {
			return {
				...option.dataValues,
				user_full_name: option.user ? option.user.dataValues.full_name : null,
				hospital_name: option.hospital ? option.hospital.dataValues.display_name : null,
				company_name: option.company ? option.company.dataValues.display_name : null,
				religion_name: option.religion ? option.religion.dataValues.display_name : null,
				bloodgroup_name: option.bloodgroup ? option.bloodgroup.dataValues.display_name : null,
				maritalstatus_name: option.maritalstatus ? option.maritalstatus.dataValues.display_name : null,
				occupation_name: option.occupation ? option.occupation.dataValues.display_name : null,
				nationality_name: option.nationality ? option.nationality.dataValues.display_name : null,
				gender_name: option.gender ? option.gender.dataValues.display_name : null,
				agerange_name: option.agerange ? option.agerange.dataValues.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 patient items
 *
 * @returns {Promise<{
 *   count: number,
 *   success: boolean,
 *   message: string
 * }>}
 */

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

		if (params.company_id) {
			filterConditions.company_id = {
				[Op.eq]: params.company_id,
			};
		}

		if (params.companiesId) {
			filterConditions.company_id = {
				[Op.in]: params.companiesId,
			};
		}

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

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

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

		// save
		await patient.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 patient
 * @param {number} id - the id of the patient
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const patient = await dbSAPPS.Patient.findByPk(id);
		if (!patient) return { success: false, message: "ID not found!" };

		// validate used in Prescription
		const usedInPrescription = await dbSAPPS.Prescription.count({
			where: {
				patient_id: id,
			},
			transaction,
		});
		if (usedInPrescription > 0) {
			throw new Error(`This patient is being used in Prescription, cannot be deleted!`);
		}

		// validate used in BloodPressureMonitoring
		const usedInBloodPressureMonitoring = await dbSAPPS.BloodPressureMonitoring.count({
			where: {
				patient_id: id,
			},
			transaction,
		});
		if (usedInBloodPressureMonitoring > 0) {
			throw new Error(`This patient is being used in BloodPressureMonitoring, cannot be deleted!`);
		}

		// delete
		await patient.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,
		};
	}
}
