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

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

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

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

/**
 * Get all shift types, optionally filtered by a list of companies.
 * @param {Object} params - The parameters to filter by.
 * @param {number[]} params.companiesId - The IDs of the companies to filter by.
 * @returns {Promise<Object>} - The response object containing the list of shift types and a success flag and message.
 */
async function getAll(params) {
	try {
		// filter
		const filterConditions = {};
		const andConditions = [];

		// precedence: company_id wins over companiesId
		if (params?.company_id) {
			filterConditions.company_id = { [Op.eq]: Number(params.company_id) };
		} else if (params?.companiesId) {
			filterConditions.company_id = { [Op.in]: params.companiesId };
		}

		// global search
		if (params?.q) {
			const q = String(params.q).trim();
			if (q) {
				andConditions.push({
					[Op.or]: [
						{ name: { [Op.like]: `%${q}%` } },
						{ display_name: { [Op.like]: `%${q}%` } },
						{ code: { [Op.like]: `%${q}%` } },
						{ start_time: { [Op.like]: `%${q}%` } },
						{ end_time: { [Op.like]: `%${q}%` } },
						{ "$company.display_name$": { [Op.like]: `%${q}%` } },
					],
				});
			}
		}

		// column filters
		if (params?.f_name) andConditions.push({ name: { [Op.like]: `%${String(params.f_name).trim()}%` } });
		if (params?.f_display_name) andConditions.push({ display_name: { [Op.like]: `%${String(params.f_display_name).trim()}%` } });
		if (params?.f_start_time) andConditions.push({ start_time: { [Op.like]: `%${String(params.f_start_time).trim()}%` } });
		if (params?.f_end_time) andConditions.push({ end_time: { [Op.like]: `%${String(params.f_end_time).trim()}%` } });
		if (params?.f_company_name) andConditions.push({ "$company.display_name$": { [Op.like]: `%${String(params.f_company_name).trim()}%` } });

		const where = { ...filterConditions };
		if (andConditions.length) where[Op.and] = andConditions;

		let shiftTypes = [];
		shiftTypes = await dbSAPPS.ShiftType.findAll({
			where,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name", "name"],
				},
			],
		});

		shiftTypes = shiftTypes.map((desigantion) => {
			return {
				...desigantion.dataValues,
				company_name: desigantion?.company?.display_name,
			};
		});

		shiftTypes = await formatWithModifier(shiftTypes);

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

/**
 * Get shift types with their respective settings.
 * @param {Object} params - An object that contains parameters to filter the shift types.
 * @param {number[]} params.companiesId - Array of company IDs to filter by.
 * @returns {Promise<Object>} - The response object containing the list of shift types and a success flag and message.
 * @example
 * const result = await option({ companiesId: [1, 2] });
 * console.log(result);
 */
async function option(params) {
	try {
		// filter
		const filterConditions = {};

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

		// must be enabled
		filterConditions.enabled = {
			[Op.eq]: true,
		};

		let options = [];
		options = await dbSAPPS.ShiftType.findAll({
			attributes: ["id", "code", "display_name", "company_id", "start_time", "end_time", "late_time", "early_time"],
			where: filterConditions,
			order: [["name", "ASC"]],
		});

		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 shift types
 *
 * @param {Object} params - The query parameters
 * @param {number[]} [params.companiesId] - The companies ID to filter by
 * @returns {Promise<{
 *   count: number,
 *   success: boolean,
 *   message: string
 * }>}
 */
async function count(params) {
	try {
		// filter
		const filterConditions = {};

		// must be enabled
		filterConditions.enabled = {
			[Op.eq]: true,
		};

		const count = await dbSAPPS.ShiftType.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 shift type
 *
 * @param {object} params - Shift type data to be created.
 * @param {string} params.name - Shift type name.
 * @param {string} params.display_name - Shift type display name.
 * @param {boolean} [params.enabled=true] - Shift type enabled status.
 * @param {number} [params.start_time] - Shift type start time.
 * @param {number} [params.end_time] - Shift type end time.
 * @param {number} [params.late_time] - Shift type late time.
 * @param {number} [params.early_time] - Shift type early time.
 * @param {number} [params.company_id] - Company ID of the shift type.
 * @param {number} [params.creation=Date.now()] - Shift type creation timestamp.
 * @param {number} [params.modified=Date.now()] - Shift type last modification timestamp.
 * @param {number} [params.owner=1] - User ID of the shift type owner.
 * @param {number} [params.modified_by=1] - User ID of the last modifier of the shift type.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the shift type creation process.
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existingName = await dbSAPPS.ShiftType.findOne({
			where: { name: params.name, company_id: params.company_id },
			transaction,
		});
		if (existingName) {
			return {
				success: false,
				message: `"${params.name}" is already taken.`,
			};
		}

		const existingDisplayName = await dbSAPPS.ShiftType.findOne({
			where: { display_name: params.display_name, company_id: params.company_id },
			transaction,
		});
		if (existingDisplayName) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		// params defaults
		if (!params.enabled) params.enabled = true;

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

		// validate existing
		const existingName = await dbSAPPS.ShiftType.findOne({
			where: {
				name: params.name,
				company_id: params.company_id,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existingName) {
			return {
				success: false,
				message: `"${params.name}" is already taken.`,
			};
		}

		const existingDisplayName = await dbSAPPS.ShiftType.findOne({
			where: {
				display_name: params.display_name,
				company_id: params.company_id,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existingDisplayName) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		// save
		await shiftType.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,
		};
	}
}

/**
 * Enable or disable a shift type
 *
 * @param {number} id - Shift type ID to be updated.
 * @param {object} params - Shift type data to be updated.
 * @param {boolean} params.enabled - Shift type enabled status.
 * @param {number} [params.modified_by] - User ID of the last modifier of the shift type.
 * @param {number} [params.modified=Date.now()] - Shift type last modification timestamp.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the shift type update process.
 */
async function enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const shiftType = await dbSAPPS.ShiftType.findByPk(id);
		if (!shiftType) return { success: false, message: "ID not found!" };

		// update params
		const updateData = {};
		updateData.enabled = params.enabled;
		if (params.modified_by) updateData.modified_by = params.modified_by;
		if (params.modified) updateData.modified = params.modified;

		// save
		await shiftType.update(updateData, { 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,
		};
	}
}

async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const shiftType = await dbSAPPS.ShiftType.findByPk(id, { transaction });
		if (!shiftType) return { success: false, message: "ID not found!" };

		// validate used in employee
		const usedInEmployee = await dbSAPPS.Employee.count({
			where: {
				shifttype_id: id,
			},
			transaction,
		});
		if (usedInEmployee > 0) {
			throw new Error(`This shift type is being used in Employee, cannot be deleted!`);
		}

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