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

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

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

			// Format holidays with modifier if they exist
			let formattedHolidays = [];
			if (holidayGroup.holidays && Array.isArray(holidayGroup.holidays)) {
				formattedHolidays = await Promise.all(
					holidayGroup.holidays.map(async (holiday) => {
						const holidayModifier = await dbSAPPS.User.findOne({
							where: {
								id: holiday.modified_by,
							},
							attributes: ["full_name"],
						});

						return {
							...(holiday.dataValues || holiday),
							modifier: holidayModifier?.full_name,
						};
					}),
				);
			}

			return {
				...holidayGroup,
				modifier: modifier?.full_name,
				holidays: formattedHolidays,
			};
		}),
	);
};

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

		// Precedence: specific company_id wins over scope companiesId
		if (params.company_id) {
			const companyId = parseInt(params.company_id, 10);
			if (!isNaN(companyId)) {
				filterConditions.company_id = {
					[Op.eq]: companyId,
				};
			}
		} else if (params.companiesId) {
			const raw = params.companiesId;
			const companiesId = Array.isArray(raw) ? raw.map((id) => parseInt(id, 10)).filter((n) => !isNaN(n)) : [];
			if (companiesId.length > 0) {
				filterConditions.company_id = {
					[Op.in]: companiesId,
				};
			}
		}

		// column-level filters
		if (params.f_code) {
			filterConditions.code = {
				[Op.iLike]: `%${params.f_code}%`,
			};
		}

		if (params.f_display_name) {
			filterConditions.display_name = {
				[Op.iLike]: `%${params.f_display_name}%`,
			};
		}

		if (params.f_company_name) {
			filterConditions["$company.display_name$"] = {
				[Op.iLike]: `%${params.f_company_name}%`,
			};
		}

		// global search across key fields
		const andConditions = [];
		if (params.q) {
			andConditions.push({
				[Op.or]: [
					{ code: { [Op.iLike]: `%${params.q}%` } },
					{ display_name: { [Op.iLike]: `%${params.q}%` } },
					{ "$company.display_name$": { [Op.iLike]: `%${params.q}%` } },
				],
			});
		}

		const whereClause = {
			...filterConditions,
			...(andConditions.length
				? {
						[Op.and]: andConditions,
					}
				: {}),
		};

		let holidayGroups = [];
		holidayGroups = await dbSAPPS.HolidayGroup.findAll({
			order: [["modified", "DESC"]],
			where: whereClause,
			include: [
				{
					model: dbSAPPS.Company,
					attributes: ["id", "display_name"],
					as: "company",
				},
				{
					model: dbSAPPS.Holiday,
					as: "holidays",
				},
			],
		});

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

		holidayGroups = await formatWithModifier(holidayGroups);

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

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

		// Precedence: specific company_id wins over scope companiesId
		if (params.company_id) {
			const companyId = parseInt(params.company_id, 10);
			if (!isNaN(companyId)) {
				filterConditions.company_id = {
					[Op.eq]: companyId,
				};
			}
		} else {
			const raw = params.companiesId;
			const companiesId = Array.isArray(raw) ? raw.map((id) => parseInt(id, 10)).filter((n) => !isNaN(n)) : [];
			if (companiesId.length > 0) {
				filterConditions.company_id = {
					[Op.in]: companiesId,
				};
			}
		}

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

		let options = [];
		options = await dbSAPPS.HolidayGroup.findAll({
			attributes: ["id", "display_name", "company_id"],
			where: filterConditions,
			order: [["display_name", "ASC"]],
			include: [
				{
					model: dbSAPPS.Company,
					attributes: ["id", "display_name"],
					as: "company",
				},
			],
		});

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

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

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

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

		const count = await dbSAPPS.HolidayGroup.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,
		};
	}
}

async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existingDisplayName = await dbSAPPS.HolidayGroup.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
		if (!params.enabled) params.enabled = true;

		// Extract holidays from params
		const holidays = params.holidays;
		delete params.holidays;

		// save
		const holidayGroup = await dbSAPPS.HolidayGroup.create(params, { transaction });

		// Create holidays if provided
		if (Array.isArray(holidays) && holidays.length > 0) {
			const holidaysData = holidays.map((holiday) => ({
				...holiday,
				holidaygroup_id: holidayGroup.id,
				enabled: holiday.enabled !== undefined ? holiday.enabled : true,
			}));

			await dbSAPPS.Holiday.bulkCreate(holidaysData, { 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 update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const holidayGroup = await dbSAPPS.HolidayGroup.findByPk(id);
		if (!holidayGroup) return { success: false, message: "ID not found!" };

		// validate existing
		const existingDisplayName = await dbSAPPS.HolidayGroup.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.`,
			};
		}

		// Extract holidays from params
		const holidays = params.holidays;
		delete params.holidays;

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

		// Handle holidays
		if (Array.isArray(holidays)) {
			// Delete existing holidays
			await dbSAPPS.Holiday.destroy({
				where: { holidaygroup_id: id },
				transaction,
			});

			// Create new holidays if provided
			if (holidays.length > 0) {
				const holidaysData = holidays.map((holiday) => ({
					...holiday,
					holidaygroup_id: id,
					enabled: holiday.enabled !== undefined ? holiday.enabled : true,
				}));

				await dbSAPPS.Holiday.bulkCreate(holidaysData, { 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 enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const holidayGroup = await dbSAPPS.HolidayGroup.findByPk(id);
		if (!holidayGroup) 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 holidayGroup.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 holidayGroup = await dbSAPPS.HolidayGroup.findByPk(id);
		if (!holidayGroup) return { success: false, message: "ID not found!" };

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