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

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

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

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

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

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

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

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

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

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

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

		let leaveAllocations = [];
		leaveAllocations = await dbSAPPS.LeaveAllocation.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name", "name"],
				},
				{
					model: dbSAPPS.LeaveType,
					as: "leavetype",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.LeavePeriod,
					as: "leaveperiod",
					attributes: ["id", "name", "display_name", "from_date", "to_date", "is_active"],
				},
				{
					model: dbSAPPS.Employee,
					as: "employee",
					attributes: ["id", "employee_number", "employee_name", "company_id"],
				},
				{
					model: dbSAPPS.User,
					as: "modifier", // pastikan alias sesuai relasi di model Attendance
					attributes: ["full_name"],
				},
			],
		});

		leaveAllocations = leaveAllocations.map((leaveAllocation) => {
			return {
				...leaveAllocation.dataValues,
				company_name: leaveAllocation?.company?.display_name,
				leavetype_name: leaveAllocation?.leavetype?.display_name,
				leaveperiod_name: leaveAllocation?.leaveperiod?.display_name,
				employee_name: leaveAllocation?.employee?.employee_name,
				modifier: leaveAllocation?.modifier?.full_name,
			};
		});

		leaveAllocations = await formatWithModifier(leaveAllocations);

		return {
			leaveAllocations,
			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 = {};

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

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

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

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

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

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

		let options = [];
		options = await dbSAPPS.LeaveAllocation.findAll({
			attributes: [
				"id",
				"name",
				"display_name",
				"leavetype_id",
				"leaveperiod_id",
				"company_id",
				"employee_id",
				"new_leaves_allocated",
				"total_leaves_allocated",
				"unused_leaves",
				"used_leaves",
				"expired_leaves",
				"leaves_pending_approval",
			],
			where: filterConditions,
			order: [["name", "ASC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name", "name"],
				},
				{
					model: dbSAPPS.LeaveType,
					as: "leavetype",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.LeavePeriod,
					as: "leaveperiod",
					attributes: ["id", "name", "display_name", "from_date", "to_date", "is_active"],
				},
				{
					model: dbSAPPS.Employee,
					as: "employee",
					attributes: ["id", "employee_number", "employee_name", "company_id"],
				},
			],
		});

		options = options.map((option) => {
			return {
				...option.dataValues,
				company_name: option?.company?.display_name,
				employee_name: option?.employee?.employee_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 = {};

		const count = await dbSAPPS.LeaveAllocation.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.LeaveAllocation.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;

		// Validate LeavePeriod exists and is active
		if (params.leaveperiod_id) {
			const leavePeriod = await dbSAPPS.LeavePeriod.findOne({
				where: { id: params.leaveperiod_id },
				transaction,
			});
			if (!leavePeriod) {
				await transaction.rollback();
				return {
					success: false,
					message: `Leave Period dengan ID ${params.leaveperiod_id} tidak ditemukan.`,
				};
			}
			if (leavePeriod.company_id !== parseInt(params.company_id)) {
				await transaction.rollback();
				return {
					success: false,
					message: `Leave Period tidak sesuai dengan company yang dipilih.`,
				};
			}
			// Validate dates are within leave period range
			const periodFromDate = new Date(leavePeriod.from_date);
			const periodToDate = new Date(leavePeriod.to_date);
			const allocFromDate = new Date(params.from_date);
			const allocToDate = new Date(params.to_date);
			if (allocFromDate < periodFromDate || allocToDate > periodToDate) {
				await transaction.rollback();
				return {
					success: false,
					message: `Tanggal Leave Allocation (${params.from_date} - ${params.to_date}) harus berada dalam periode Leave Period (${leavePeriod.from_date} - ${leavePeriod.to_date}).`,
				};
			}
		}

		// Validate LeaveType exists and matches company
		if (params.leavetype_id) {
			const leaveType = await dbSAPPS.LeaveType.findOne({
				where: { id: params.leavetype_id },
				transaction,
			});
			if (!leaveType) {
				await transaction.rollback();
				return {
					success: false,
					message: `Leave Type dengan ID ${params.leavetype_id} tidak ditemukan.`,
				};
			}
			if (leaveType.company_id !== parseInt(params.company_id)) {
				await transaction.rollback();
				return {
					success: false,
					message: `Leave Type tidak sesuai dengan company yang dipilih.`,
				};
			}
		}

		// Validate Employee exists and matches company
		if (params.employee_id) {
			const employee = await dbSAPPS.Employee.findOne({
				where: { id: params.employee_id },
				transaction,
			});
			if (!employee) {
				await transaction.rollback();
				return {
					success: false,
					message: `Employee dengan ID ${params.employee_id} tidak ditemukan.`,
				};
			}
			if (employee.company_id !== parseInt(params.company_id)) {
				await transaction.rollback();
				return {
					success: false,
					message: `Employee tidak sesuai dengan company yang dipilih.`,
				};
			}
		}

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

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

		// Validate LeavePeriod exists and is active (if being changed)
		if (params.leaveperiod_id && params.leaveperiod_id !== leaveAllocation.leaveperiod_id) {
			const leavePeriod = await dbSAPPS.LeavePeriod.findOne({
				where: { id: params.leaveperiod_id },
				transaction,
			});
			if (!leavePeriod) {
				await transaction.rollback();
				return {
					success: false,
					message: `Leave Period dengan ID ${params.leaveperiod_id} tidak ditemukan.`,
				};
			}
			if (leavePeriod.company_id !== parseInt(params.company_id || leaveAllocation.company_id)) {
				await transaction.rollback();
				return {
					success: false,
					message: `Leave Period tidak sesuai dengan company yang dipilih.`,
				};
			}
			// Validate dates are within leave period range
			const periodFromDate = new Date(leavePeriod.from_date);
			const periodToDate = new Date(leavePeriod.to_date);
			const allocFromDate = new Date(params.from_date || leaveAllocation.from_date);
			const allocToDate = new Date(params.to_date || leaveAllocation.to_date);
			if (allocFromDate < periodFromDate || allocToDate > periodToDate) {
				await transaction.rollback();
				return {
					success: false,
					message: `Tanggal Leave Allocation (${allocFromDate.toISOString().split('T')[0]} - ${allocToDate.toISOString().split('T')[0]}) harus berada dalam periode Leave Period (${leavePeriod.from_date} - ${leavePeriod.to_date}).`,
				};
			}
		}

		// Validate LeaveType exists and matches company (if being changed)
		if (params.leavetype_id && params.leavetype_id !== leaveAllocation.leavetype_id) {
			const leaveType = await dbSAPPS.LeaveType.findOne({
				where: { id: params.leavetype_id },
				transaction,
			});
			if (!leaveType) {
				await transaction.rollback();
				return {
					success: false,
					message: `Leave Type dengan ID ${params.leavetype_id} tidak ditemukan.`,
				};
			}
			if (leaveType.company_id !== parseInt(params.company_id || leaveAllocation.company_id)) {
				await transaction.rollback();
				return {
					success: false,
					message: `Leave Type tidak sesuai dengan company yang dipilih.`,
				};
			}
		}

		// Validate Employee exists and matches company (if being changed)
		if (params.employee_id && params.employee_id !== leaveAllocation.employee_id) {
			const employee = await dbSAPPS.Employee.findOne({
				where: { id: params.employee_id },
				transaction,
			});
			if (!employee) {
				await transaction.rollback();
				return {
					success: false,
					message: `Employee dengan ID ${params.employee_id} tidak ditemukan.`,
				};
			}
			if (employee.company_id !== parseInt(params.company_id || leaveAllocation.company_id)) {
				await transaction.rollback();
				return {
					success: false,
					message: `Employee tidak sesuai dengan company yang dipilih.`,
				};
			}
		}

		// save
		await leaveAllocation.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 _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const leaveAllocation = await dbSAPPS.LeaveAllocation.findByPk(id, {
			transaction,
		});
		if (!leaveAllocation) return { success: false, message: "ID not found!" };

		// validate used in leaveApplication
		const usedInLeaveApplication = await dbSAPPS.LeaveApplication.count({
			where: {
				leaveallocation_id: id,
			},
			transaction,
		});
		if (usedInLeaveApplication > 0) {
			throw new Error(`This leave allocation is being used in Leave Application, cannot be deleted!`);
		}

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