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

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

/**
 * Get all leave periods with company filter (company_id precedence over companiesId), q and f_*.
 * @param {Object} params - { company_id?, companiesId?, q?, f_name?, f_display_name?, f_company_name?, f_from_date?, f_to_date?, ... }
 */
async function getAll(params) {
	try {
		const filterConditions = {};
		const andConditions = [];

		// Precedence: company_id wins over companiesId (§6.2)
		if (params?.company_id != null && String(params.company_id).trim() !== "") {
			const companyId = Number(params.company_id);
			if (!Number.isNaN(companyId)) {
				filterConditions.company_id = { [Op.eq]: companyId };
			}
		} else if (params?.companiesId != null) {
			const raw = params.companiesId;
			const companiesId = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : [raw];
			const parsed = companiesId.map((v) => Number(String(v).trim())).filter((v) => !Number.isNaN(v));
			if (parsed.length) {
				filterConditions.company_id = { [Op.in]: parsed };
			}
		}

		// Global search (q)
		const q = typeof params?.q === "string" ? params.q.trim() : "";
		if (q) {
			andConditions.push({
				[Op.or]: [
					{ name: { [Op.like]: `%${q}%` } },
					{ display_name: { [Op.like]: `%${q}%` } },
					{ "$company.display_name$": { [Op.like]: `%${q}%` } },
				],
			});
		}

		if (params?.f_name && String(params.f_name).trim()) {
			andConditions.push({ name: { [Op.like]: `%${String(params.f_name).trim()}%` } });
		}
		if (params?.f_display_name && String(params.f_display_name).trim()) {
			andConditions.push({ display_name: { [Op.like]: `%${String(params.f_display_name).trim()}%` } });
		}
		if (params?.f_company_name && String(params.f_company_name).trim()) {
			andConditions.push({ "$company.display_name$": { [Op.like]: `%${String(params.f_company_name).trim()}%` } });
		}
		if (params?.f_from_date && String(params.f_from_date).trim()) {
			andConditions.push({ from_date: { [Op.like]: `%${String(params.f_from_date).trim()}%` } });
		}
		if (params?.f_to_date && String(params.f_to_date).trim()) {
			andConditions.push({ to_date: { [Op.like]: `%${String(params.f_to_date).trim()}%` } });
		}

		if (params.is_active != null) {
			filterConditions.is_active = { [Op.eq]: !!params.is_active };
		}

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

		let leavePeriods = [];
		leavePeriods = await dbSAPPS.LeavePeriod.findAll({
			where: whereClause,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name", "name"],
					required: !!q || !!(params?.f_company_name && String(params.f_company_name).trim()),
				},
			],
		});

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

		leavePeriods = await formatWithModifier(leavePeriods);

		return {
			leavePeriods,
			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 {
		const filterConditions = {};
		// Precedence: company_id wins over companiesId
		if (params?.company_id != null && String(params.company_id).trim() !== "") {
			const companyId = Number(params.company_id);
			if (!Number.isNaN(companyId)) {
				filterConditions.company_id = { [Op.eq]: companyId };
			}
		} else if (params?.companiesId != null) {
			const raw = params.companiesId;
			const companiesId = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : [raw];
			const parsed = companiesId.map((v) => Number(String(v).trim())).filter((v) => !Number.isNaN(v));
			if (parsed.length) {
				filterConditions.company_id = { [Op.in]: parsed };
			}
		}

		if (params.from_date && params.to_date) {
			filterConditions.from_date = {
				[Op.lte]: params.from_date,
			};
			filterConditions.to_date = {
				[Op.gte]: params.to_date,
			};
		}

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

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

		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 {
		const filterConditions = {};
		if (params?.company_id != null && String(params.company_id).trim() !== "") {
			const companyId = Number(params.company_id);
			if (!Number.isNaN(companyId)) {
				filterConditions.company_id = { [Op.eq]: companyId };
			}
		} else if (params?.companiesId != null) {
			const raw = params.companiesId;
			const companiesId = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : [raw];
			const parsed = companiesId.map((v) => Number(String(v).trim())).filter((v) => !Number.isNaN(v));
			if (parsed.length) {
				filterConditions.company_id = { [Op.in]: parsed };
			}
		}

		if (params.from_date && params.to_date) {
			filterConditions.from_date = {
				[Op.lte]: params.from_date,
			};
			filterConditions.to_date = {
				[Op.gte]: params.to_date,
			};
		}

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

		const count = await dbSAPPS.LeavePeriod.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 existing = await dbSAPPS.LeavePeriod.findOne({
			where: {
				display_name: params.display_name,
				name: params.name,
				company_id: params.company_id,
			},
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		if (!params.enabled) params.enabled = true;
		if (!params.is_active) params.is_active = true;

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

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

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

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

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

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

		// save
		await leavePeriod.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 leavePeriod = await dbSAPPS.LeavePeriod.findByPk(id, { transaction });
		if (!leavePeriod) return { success: false, message: "ID not found!" };

		// validate used in leaveAllocation
		const usedInLeaveAllocation = await dbSAPPS.LeaveAllocation.count({
			where: {
				leaveperiod_id: id,
			},
			transaction,
		});
		if (usedInLeaveAllocation > 0) {
			throw new Error(
				`This leave period is being used in Leave Allocation, cannot be deleted!`
			);
		}		

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