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

module.exports = {
	getAll,
};

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

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

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

		if (params.date) {
			// Jika hanya ada params.date, cari allocation yang mencakup tanggal tersebut
			filterConditions.from_date = {
				[Op.lte]: params.date,
			};
			filterConditions.to_date = {
				[Op.gte]: params.date,
			};
		}

		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"],
				},
			],
		});

		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,
			};
		});

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