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

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

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

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

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

		let budgetDepartments = [];
		budgetDepartments = await dbSAPPS.BudgetDepartment.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name", "name"],
				},
				{
					model: dbSAPPS.BudgetDepartment,
					as: "parent",
					attributes: ["id", "name", "department_name"], // field parent yang ingin ditampilkan
				},
				{
					model: dbSAPPS.BudgetApprover,
					as: "budgetapprovers",
					attributes: [
						"id",
						"budgetdepartment_id",
						"company_id",
						"ba_employee_id",
						"ba_full_name",
						"ba_email",
						"ba_designation_name",
						"ba_territory_name",
						"ba_username",
						"fin_employee_id",
						"fin_full_name",
						"fin_email",
						"fin_designation_name",
						"fin_territory_name",
						"fin_username",
					],
				},
				{
					model: dbSAPPS.User,
					as: "modifier", // pastikan alias sesuai relasi di model Attendance
					attributes: ["full_name"],
				},
			],
		});

		budgetDepartments = budgetDepartments.map((budgetDepartment) => {
			return {
				...budgetDepartment.dataValues,
				company_name: budgetDepartment?.company?.display_name,
				modifier: budgetDepartment?.modifier?.full_name,
				parent_department_name: budgetDepartment?.parent?.name,
			};
		});

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

/**
 * Get options
 */
async function option(params) {
	try {
		// filter
		const filterConditions = {};

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

		if (params.companiesId) {
			filterConditions.company_id = {
				[Op.in]: params.companiesId,
			};
		}
		if (params.is_group) {
			filterConditions.is_group = {
				// true is always sent as a string from the frontend
				[Op.eq]: params.is_group,
			};
		}

		// must be disabled
		filterConditions.disabled = {
			[Op.eq]: false,
		};

		let options = [];
		options = await dbSAPPS.BudgetDepartment.findAll({
			attributes: ["id", "name", "department_name", "company_id"],
			where: filterConditions,
			order: [["name", "ASC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name", "name"],
				},
				{
					model: dbSAPPS.BudgetApprover,
					as: "budgetapprovers",
					attributes: [
						"id",
						"budgetdepartment_id",
						"company_id",
						"ba_employee_id",
						"ba_full_name",
						"ba_email",
						"ba_designation_name",
						"ba_territory_name",
						"ba_username",
						"fin_employee_id",
						"fin_full_name",
						"fin_email",
						"fin_designation_name",
						"fin_territory_name",
						"fin_username",
					],
				},
			],
		});

		options = options.map((option) => {
			return {
				...option.dataValues,
				company_name: option?.company?.display_name,
				ba_employee_id: option?.budgetapprovers[0]?.ba_employee_id,
				ba_full_name: option?.budgetapprovers[0]?.ba_full_name,
				ba_email: option?.budgetapprovers[0]?.ba_email,
				ba_designation_name: option?.budgetapprovers[0]?.ba_designation_name,
				ba_territory_name: option?.budgetapprovers[0]?.ba_territory_name,
				ba_username: option?.budgetapprovers[0]?.ba_username,
				fin_employee_id: option?.budgetapprovers[0]?.fin_employee_id,
				fin_full_name: option?.budgetapprovers[0]?.fin_full_name,
				fin_email: option?.budgetapprovers[0]?.fin_email,
				fin_designation_name: option?.budgetapprovers[0]?.fin_designation_name,
				fin_territory_name: option?.budgetapprovers[0]?.fin_territory_name,
				fin_username: option?.budgetapprovers[0]?.fin_username,
			};
		});

		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
 */
async function count(params) {
	try {
		// filter
		const filterConditions = {};

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

		const count = await dbSAPPS.BudgetDepartment.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,
		};
	}
}

/**
 * Creates a new
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existing = await dbSAPPS.BudgetDepartment.findOne({
			where: {
				name: params.name,
				company_id: params.company_id,
			},
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		if (!params.disabled) params.disabled = false;

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

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

		// validate existing
		const existing = await dbSAPPS.BudgetDepartment.findOne({
			where: {
				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 budgetDepartment.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,
		};
	}
}

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

		params.disabled = params.enabled;

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

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

/**
 * Deletes
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const budgetDepartment = await dbSAPPS.BudgetDepartment.findByPk(id, { transaction });
		if (!budgetDepartment) return { success: false, message: "ID not found!" };

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