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

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

/**
 * Retrieves all Budgeting with their parent Budgeting title.
 */
async function getAll(params) {
	try {
		// filter
		const filterConditions = {};

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

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

		budgetings = budgetings.map((budgeting) => {
			return {
				...budgeting.dataValues,
				company_name: budgeting?.company?.display_name,
				department_name: budgeting?.department?.display_name,
				employee_name: budgeting?.employee?.employee_name,
				modifier: budgeting?.modifier?.full_name,
			};
		});

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

/**
 * Get Budgeting items with their respective settings.
 */
async function option(params) {
	try {
		// filter
		const filterConditions = {};

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

		let options = [];
		options = await dbSAPPS.Budgeting.findAll({
			attributes: ["id", "name", "display_name"],
			where: filterConditions,
			order: [["name", "ASC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Department,
					as: "department",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.Employee,
					as: "employee",
					attributes: ["id", "employee_name"],
				},
				{
					model: dbSAPPS.BudgetingItem,
					as: "budgetingitems",
				},
			],
		});

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

/**
 * Count active Budgeting items
 */

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

		const count = await dbSAPPS.Budgeting.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 Budgeting item.
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existing = await dbSAPPS.Budgeting.findOne({
			where: { name: params.name, display_name: params.display_name },
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		// save
		const budget = await dbSAPPS.Budgeting.create(params, { transaction });

		if (Array.isArray(params.budgetaccounts) && params.budgetaccounts.length > 0) {
			// create budget accounts
			const budgetAccountsData = params.budgetaccounts.map((budgetAccount) => ({
				...budgetAccount,
				creation: Date.now(),
				modified: Date.now(),
				modified_by: params.modified_by,
				owner: params.owner,
				budgeting_id: budget?.id,
				company_id: params.company_id,
				department: params.department_id,
				employee: params.employee_id,
			}));

			// save
			await dbSAPPS.BudgetingAccount.bulkCreate(budgetAccountsData, {
				transaction,
			});
		}

		if (Array.isArray(params.budgetitems) && params.budgetitems.length > 0) {
			// create budget items
			const budgetItemsData = params.budgetitems.map((budgetItem) => ({
				...budgetItem,
				creation: Date.now(),
				modified: Date.now(),
				modified_by: params.modified_by,
				owner: params.owner,
				budgeting_id: budget?.id,
				company_id: params.company_id,
				department: params.department_id,
				employee: params.employee_id,
			}));

			// save
			await dbSAPPS.BudgetingItem.bulkCreate(budgetItemsData, {
				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 Budgeting item.
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const budget = await dbSAPPS.Budgeting.findByPk(id);
		if (!budget) return { success: false, message: "ID not found!" };

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

		// save
		await budget.update(params, { transaction });

		// budget accounts
		if (Array.isArray(params.budgetaccounts) && params.budgetaccounts.length > 0) {
			await dbSAPPS.BudgetingAccount.destroy({
				where: { budgeting_id: id },
				transaction,
			});

			// create budgets
			const budgetAccountsData = params.budgetaccounts.map((budgetAccount) => ({
				...budgetAccount,
				creation: Date.now(),
				modified: Date.now(),
				modified_by: params.modified_by,
				owner: params.owner,
				budgeting_id: JSON.parse(id),
				company_id: budgetAccount.company_id || params.company_id,
				department: budgetAccount.department || params.department_id,
				employee: budgetAccount.employee || params.employee_id,
			}));

			// save
			await dbSAPPS.BudgetingAccount.bulkCreate(budgetAccountsData, {
				transaction,
			});
		} else {
			// delete budgets
			await dbSAPPS.BudgetingAccount.destroy({
				where: { budgeting_id: id },
				transaction,
			});
		}

		// budget items
		if (Array.isArray(params.budgetitems) && params.budgetitems.length > 0) {
			await dbSAPPS.BudgetingItem.destroy({
				where: { budgeting_id: id },
				transaction,
			});

			// create budgets
			const budgetItemsData = params.budgetitems.map((budgetItem) => ({
				...budgetItem,
				creation: Date.now(),
				modified: Date.now(),
				modified_by: params.modified_by,
				owner: params.owner,
				budgeting_id: JSON.parse(id),
				company_id: budgetItem.company_id || params.company_id,
				department: budgetItem.department || params.department_id,
				employee: budgetItem.employee || params.employee_id,
			}));

			// save
			await dbSAPPS.BudgetingItem.bulkCreate(budgetItemsData, {
				transaction,
			});
		} else {
			// delete budgets
			await dbSAPPS.BudgetingItem.destroy({
				where: { budgeting_id: id },
				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,
		};
	}
}

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

		// delete budget accounts
		await dbSAPPS.BudgetingAccount.destroy({
			where: { budgeting_id: id },
			transaction,
		});

		// delete budgetitem
		await dbSAPPS.BudgetingItem.destroy({
			where: { budgeting_id: id },
			transaction,
		});

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