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.companiesId) {
			filterConditions.company_id = {
				[Op.in]: params.companiesId,
			};
		}

		if (params.company_id) {
			filterConditions.company_id = {
				[Op.in]: 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.leavetype_id) {
			filterConditions.leavetype_id = {
				[Op.eq]: params.leavetype_id,
			};
		}

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

		if (params.from_date && params.to_date) {
			filterConditions.date = {
				[Op.between]: [params.from_date, params.to_date],
			};
		} else if (params.date) {
			filterConditions.date = {
				[Op.eq]: params.date,
			};
		}

		let attendanceRequests = [];
		attendanceRequests = await dbSAPPS.AttendanceRequest.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name", "name"],
				},
				{
					model: dbSAPPS.Employee,
					as: "employee",
					attributes: ["id", "employee_name", "employee_number"],
				},
				{
					model: dbSAPPS.Department,
					as: "department",
					attributes: ["id", "display_name"],
				},
				{
					model: dbSAPPS.User,
					as: "modifier", // pastikan alias sesuai relasi di model Attendance
					attributes: ["full_name"],
				},
				{
					model: dbSAPPS.Employee,
					as: "leaveapprover_name", // pastikan alias sesuai relasi di model attendanceRequest
					attributes: ["employee_name"],
				},
			],
		});

		attendanceRequests = attendanceRequests.map((attendanceRequest) => {
			return {
				...attendanceRequest.dataValues,
				company_name: attendanceRequest?.company?.display_name,
				employee_name: attendanceRequest?.employee?.employee_name,
				leavetype_name: attendanceRequest?.leavetype?.display_name,
				department_name: attendanceRequest?.department?.display_name,
				modifier: attendanceRequest?.modifier?.full_name,
				leaveapprover_name: attendanceRequest?.leaveapprover_name?.employee_name,
			};
		});

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