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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		let budgetItems = [];
		budgetItems = await dbSAPPS.BudgetItem.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name"],
				},
				{
					model: dbSAPPS.BudgetDepartment,
					as: "budgetdepartment",
					attributes: ["id", "name", "department_name"],
				},
				{
					model: dbSAPPS.BudgetCategory,
					as: "budgetcategory",
					attributes: ["id", "code", "name", "display_name"],
				},
				{
					model: dbSAPPS.BudgetClassification,
					as: "budgetclassification",
					attributes: ["id", "code", "name", "display_name"],
				},
				{
					model: dbSAPPS.BudgetUnitOfMeasurement,
					as: "budgetunitofmeasurement",
					attributes: ["id", "code", "name", "display_name"],
				},
				{
					model: dbSAPPS.BudgetAccount,
					as: "budgetaccount",
					attributes: ["id", "name", "account_id"],
					include: [
						{
							model: dbSAPPS.Account,
							as: "account",
							attributes: ["id", "name"],
						},
					],
				},
				{
					model: dbSAPPS.User,
					as: "modifier",
					attributes: ["full_name"],
				},
			],
		});

		budgetItems = budgetItems.map((budgetItem) => {
			return {
				...budgetItem.dataValues,
				company_name: budgetItem?.company?.display_name,
				budgetcategory_name: budgetItem?.budgetcategory?.name,
				budgetclassification_name: budgetItem?.budgetclassification?.name,
				budgetunitofmeasurement_name: budgetItem?.budgetunitofmeasurement?.name,
				budgetdepartment_name: budgetItem?.budgetdepartment?.name,
				budgetaccount_name: budgetItem?.budgetaccount?.name,
				account_name: budgetItem?.budgetaccount?.account?.name,
				modifier: budgetItem?.modifier?.full_name,
			};
		});

		return {
			budgetItems,
			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.budgetitem_id) {
			filterConditions.id = {
				[Op.eq]: params.budgetitem_id,
			};
		}

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

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

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

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

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

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

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

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

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

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

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

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

		let options = [];
		options = await dbSAPPS.BudgetItem.findAll({
			where: filterConditions,
			attributes: [
				"id",
				"name",
				"item_code",
				"item_name",
				"specifications",
				"description",
				"default_price",
				"company_id",
				"budgetdepartment_id",
				"budgetcategory_id",
				"budgetclassification_id",
				"budgetunitofmeasurement_id",
				"budgetaccount_id",
			],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name"],
				},
				{
					model: dbSAPPS.BudgetDepartment,
					as: "budgetdepartment",
					attributes: ["id", "name", "department_name"],
				},
				{
					model: dbSAPPS.BudgetCategory,
					as: "budgetcategory",
					attributes: ["id", "code", "name", "display_name"],
				},
				{
					model: dbSAPPS.BudgetClassification,
					as: "budgetclassification",
					attributes: ["id", "code", "name", "display_name"],
				},
				{
					model: dbSAPPS.BudgetUnitOfMeasurement,
					as: "budgetunitofmeasurement",
					attributes: ["id", "code", "name", "display_name"],
				},
				{
					model: dbSAPPS.BudgetAccount,
					as: "budgetaccount",
					attributes: ["id", "name", "account_id"],
					include: [
						{
							model: dbSAPPS.Account,
							as: "account",
							attributes: ["id", "name"],
						},
					],
				},
			],
			order: [["name", "ASC"]],
		});

		options = options.map((option) => {
			return {
				...option.dataValues,
				company_name: option?.company?.display_name,
				budgetcategory_name: option?.budgetcategory?.name,
				budgetclassification_name: option?.budgetclassification?.name,
				budgetunitofmeasurement_name: option?.budgetunitofmeasurement?.name,
				budgetdepartment_name: option?.budgetdepartment?.name,
				budgetaccount_name: option?.budgetaccount?.name,
				account_name: option?.budgetaccount?.account?.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 = {};

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

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

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

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

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

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

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

		await transaction.commit();
		return {
			id: budgetItem?.id,
			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 budgetItem = await dbSAPPS.BudgetItem.findByPk(id);
		if (!budgetItem) return { success: false, message: "ID not found!" };

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

		// save
		await budgetItem.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 budgetItem = await dbSAPPS.BudgetItem.findByPk(id);
		if (!budgetItem) 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 budgetItem.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,
		};
	}
}

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

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