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

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

/**
 * Retrieves all
 */
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,
			};
		}

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

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

		let budgetPlans = [];
		budgetPlans = await dbSAPPS.BudgetPlan.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.BudgetDepartment,
					as: "budgetdepartment",
					attributes: ["id", "name"],
				},
				{
					model: dbSAPPS.BudgetPlanItem,
					as: "budgetplanitems",
					include: [
						{
							model: dbSAPPS.BudgetItem,
							as: "budgetitem",
							attributes: [
								"id",
								"item_code",
								"item_name",
								"specifications",
								"description",
								"default_price",
								"budgetaccount_id",
								"budgetunitofmeasurement_id",
								"budgetcategory_id",
								"budgetclassification_id",
								"budgetdepartment_id",
								"company_id",
							],
							include: [
								{
									model: dbSAPPS.BudgetAccount,
									as: "budgetaccount",
									attributes: ["id", "name"],
									include: [
										{
											model: dbSAPPS.Account,
											as: "account",
											attributes: ["id", "name"],
										},
									],
								},
								{
									model: dbSAPPS.BudgetUnitOfMeasurement,
									as: "budgetunitofmeasurement",
									attributes: ["id", "name"],
								},
								{
									model: dbSAPPS.BudgetCategory,
									as: "budgetcategory",
									attributes: ["id", "name"],
								},
								{
									model: dbSAPPS.BudgetClassification,
									as: "budgetclassification",
									attributes: ["id", "name"],
								},
								{
									model: dbSAPPS.BudgetDepartment,
									as: "budgetdepartment",
									attributes: ["id", "name"],
								},
								{
									model: dbSAPPS.Company,
									as: "company",
									attributes: ["id", "name"],
								},
								{
									model: dbSAPPS.User,
									as: "modifier",
									attributes: ["full_name"],
								},
							],
						},
					],
					order: [["id", "DESC"]],
				},
				{
					model: dbSAPPS.User,
					as: "modifier",
					attributes: ["full_name"],
				},
			],
		});

		budgetPlans = budgetPlans.map((budgetPlan) => {
			return {
				...budgetPlan.dataValues,
				company_name: budgetPlan?.company?.display_name,
				budgetdepartment_name: budgetPlan?.budgetdepartment?.name,
				budgetplanitem_count: budgetPlan?.budgetplanitem?.length,
				budgetplanitems: budgetPlan?.budgetplanitems.map((bpi) => ({
					...bpi.dataValues,
					account_name: bpi?.budgetitem?.budgetaccount?.account?.name,
					budgetaccount_name: bpi?.budgetitem?.budgetaccount?.name,
					budgetunitofmeasurement_name: bpi?.budgetitem?.budgetunitofmeasurement?.name,
					budgetcategory_name: bpi?.budgetitem?.budgetcategory?.name,
					budgetclassification_name: bpi?.budgetitem?.budgetclassification?.name,
					budgetdepartment_name: bpi?.budgetitem?.budgetdepartment?.name,
					company_name: bpi?.budgetitem?.company?.name,
					modifier: bpi?.budgetitem?.modifier?.full_name,
				})),
				modifier: budgetPlan?.modifier?.name,
			};
		});

		return {
			budgetPlans,
			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?.budgetdepartment_id) {
			filterConditions.budgetdepartment_id = {
				[Op.eq]: params?.budgetdepartment_id,
			};
		}

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

		let options = [];
		options = await dbSAPPS.BudgetPlan.findAll({
			attributes: ["id", "name", "display_name"],
			where: filterConditions,
			order: [["name", "ASC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
			],
		});

		options = options.map((option) => {
			return {
				...option.dataValues,
				company_name: option?.company?.display_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
 */

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

		const count = await dbSAPPS.BudgetPlan.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.BudgetPlan.findOne({
			where: { company_id: params.company_id, budgetdepartment_id: params.budgetdepartment_id, fiscal_year: params.fiscal_year },
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `is already taken.`,
			};
		}

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

		if (Array.isArray(params.budgetplanitems) && params.budgetplanitems.length > 0) {
			// create budgetplanitems
			const budgetPlanItemsData = params.budgetplanitems.map((budgetplanitem) => ({
				...budgetplanitem,
				creation: params.creation,
				modified: params.modified,
				modified_by: params.modified_by,
				owner: params.owner,
				budgetplan_id: budgetPlan.id,
				status: "Draft",
			}));

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

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

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

		if (Array.isArray(params.budgetplanitems) && params.budgetplanitems.length > 0) {
			await dbSAPPS.BudgetPlanItem.destroy({
				where: { budgetplan_id: id },
				transaction,
			});

			// create budgetplanitems
			const budgetPlanItemsData = params.budgetplanitems.map((budgetplanitem) => ({
				...budgetplanitem,
				id: null,
				budgetplan_id: JSON.parse(id),
				creation: budgetplanitem.creation,
				owner: budgetplanitem.owner,
				status: !budgetplanitem.status ? "Draft" : budgetplanitem.status,
			}));

			// save
			await dbSAPPS.BudgetPlanItem.bulkCreate(budgetPlanItemsData, {
				transaction,
			});
		} else {
			// delete budgetplanitem
			await dbSAPPS.BudgetPlanItem.destroy({
				where: { budgetplan_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,
		};
	}
}

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

		// validation
		if (!id || !params.budgetplan_id) {
			return {
				success: false,
				message: "ID and Budget Plan ID are required!",
			};
		}

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

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

		// delete budgetplanitem
		await dbSAPPS.BudgetPlanItem.destroy({
			where: { budgetplan_id: id },
			transaction,
		});

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