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

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

const formatWithModifier = async (employees) => {
	return Promise.all(
		employees.map(async (employee) => {
			const modifier = await dbSAPPS.User.findOne({
				where: {
					id: employee.modified_by,
				},
				attributes: ["full_name"],
			});

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

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

		if (params?.usersId) {
			filterConditions.user_id = {
				[Op.in]: params?.usersId,
			};
		}

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

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

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

		if (params?.departmentsId) {
			filterConditions.department_id = {
				[Op.in]: params?.departmentsId,
			};
		}

		if (params?.designationsId) {
			filterConditions.designation_id = {
				[Op.in]: params?.designationsId,
			};
		}

		let employees = [];
		employees = await dbSAPPS.Employee.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.User,
					as: "user",
					attributes: ["id", "email", "full_name"],
				},
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name"],
				},
				{
					model: dbSAPPS.Department,
					as: "department",
					attributes: ["id", "display_name"],
				},
				{
					model: dbSAPPS.Designation,
					as: "designation",
					attributes: ["id", "display_name"],
				},
				{
					model: dbSAPPS.ShiftType,
					as: "shifttype",
					attributes: [
						"id",
						"enabled",
						"name",
						"display_name",
						"code",
						"start_time",
						"end_time",
						"late_time",
						"early_time",
						"duration_break",
						"start_date_ramadhan",
						"end_date_ramadhan",
						"start_time_ramadhan",
						"end_time_ramadhan",
						"late_time_ramadhan",
						"early_time_ramadhan",
						"duration_break_ramadhan",
						"enable_auto_attendance",
						"location",
						"holidaygroup_id",
						"company_id",
					],
				},
				{
					model: dbSAPPS.User,
					as: "modifier", // pastikan alias sesuai relasi di model Attendance
					attributes: ["full_name"],
				},
			],
		});

		// update relation
		employees = employees.map((employee) => {
			return {
				...employee.dataValues,
				user_name: employee?.user?.full_name,
				shifttype_name: employee?.shifttype?.display_name,
				company_name: employee?.company?.display_name,
				department_name: employee?.department?.display_name,
				designation_name: employee?.designation?.display_name,
				modifier: employee?.modifier?.full_name,
				email: employee?.user?.email,
			};
		});

		// modifier
		// employees = await formatWithModifier(employees);

		return {
			employees,
			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?.usersId) {
			filterConditions.user_id = {
				[Op.in]: params?.usersId,
			};
		}

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

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

		if (params?.departmentsId) {
			filterConditions.department_id = {
				[Op.in]: params?.departmentsId,
			};
		}

		if (params?.designationsId) {
			filterConditions.designation_id = {
				[Op.in]: params?.designationsId,
			};
		}

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

		let options = [];
		options = await dbSAPPS.Employee.findAll({
			attributes: ["id", "employee_name", "employee_number", "user_id", "company_id", "department_id", "designation_id", "shifttype_id", "use_workflow"],
			where: filterConditions,
			order: [["employee_name", "ASC"]],
			include: [
				{
					model: dbSAPPS.User,
					as: "user",
					attributes: ["id", "email", "full_name"],
				},
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Department,
					as: "department",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Designation,
					as: "designation",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.ShiftType,
					as: "shifttype",
					attributes: [
						"id",
						"enabled",
						"name",
						"display_name",
						"code",
						"start_time",
						"end_time",
						"late_time",
						"early_time",
						"duration_break",
						"start_date_ramadhan",
						"end_date_ramadhan",
						"start_time_ramadhan",
						"end_time_ramadhan",
						"late_time_ramadhan",
						"early_time_ramadhan",
						"duration_break_ramadhan",
						"enable_auto_attendance",
						"location",
						"holidaygroup_id",
						"company_id",
					],
				},
			],
		});

		const territories = await dbSAPPS.EmployeeTerritory.findAll({
			where: {
				employee_id: {
					[Op.in]: options.map((option) => option.id),
				},
			},
			include: [
				{
					model: dbSAPPS.Territory,
					as: "territory",
					attributes: ["id", "name", "display_name"],
				},
			],
			attributes: ["employee_id", "territory_id"],
		});

		// update relation
		options = options.map((option) => {
			return {
				...option.dataValues,
				company_name: option?.company?.display_name,
				user_id: option?.user?.id,
				user_full_name: option?.user?.full_name,
				shifttype_name: option?.shifttype?.display_name,
				department_name: option?.department?.display_name,
				designation_name: option?.designation?.display_name,
				email: option?.user?.email,
				shifttype_id: option?.shifttype?.id,
				department_id: option?.department?.id,
				designation_id: option?.designation?.id,
				territory_name: territories
					.filter((territory) => territory.employee_id === option.id)
					.map((territory) => territory.territory.display_name)
					.join(", "),
			};
		});

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

/**
 * Count all enabled employees
 *
 * @returns {Promise<{
 *   success: boolean,
 *   count: number,
 *   message: string
 * }>}
 */
async function count(params) {
	try {
		// filter
		const filterConditions = {};

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

		const count = await dbSAPPS.Employee.count({
			where: filterConditions,
		});

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

		if (params.employee_number && params.employee_number !== "") {
			const existingNumber = await dbSAPPS.Employee.findOne({
				where: {
					employee_number: params.employee_number,
					company_id: params.company_id,
				},
				transaction,
			});
			if (existingNumber) {
				return {
					success: false,
					message: `"${params.employee_number}" is already taken.`,
				};
			}
		}

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

		if (params.user_id) {
			const existingUserCompany = await dbSAPPS.UserCompany.findOne({
				where: {
					user_id: params.user_id,
					company_id: params.company_id,
				},
				transaction,
			});
			if (!existingUserCompany) {
				await dbSAPPS.UserCompany.create(
					{
						user_id: params.user_id,
						company_id: params.company_id,
					},
					{ transaction }
				);
			}
		}

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

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

		if (params.employee_number && params.employee_number !== "") {
			const existingNumber = await dbSAPPS.Employee.findOne({
				where: {
					employee_number: params.employee_number,
					company_id: params.company_id,
					id: {
						[Op.ne]: id,
					},
				},
				transaction,
			});
			if (existingNumber) {
				return {
					success: false,
					message: `"${params.employee_number}" is already taken.`,
				};
			}
		}

		if (params.user_id) {
			const existingUserCompany = await dbSAPPS.UserCompany.findOne({
				where: {
					user_id: params.user_id,
					company_id: params.company_id,
				},
				transaction,
			});
			if (!existingUserCompany) {
				await dbSAPPS.UserCompany.create(
					{
						user_id: params.user_id,
						company_id: params.company_id,
					},
					{ transaction }
				);
			}
		}

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

		// validate used in attendance
		const usedInAttendance = await dbSAPPS.Attendance.count({
			where: {
				employee_id: id,
			},
			transaction,
		});
		if (usedInAttendance > 0) {
			throw new Error(`This employee is being used in Attendance, cannot be deleted!`);
		}

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