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.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.id = {
				[Op.eq]: params.budgetclassification_id,
			};
		}

		let budgetClassifications = [];
		budgetClassifications = await dbSAPPS.BudgetClassification.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name"],
				},
				{
					model: dbSAPPS.BudgetCategory,
					as: "budgetcategory",
					attributes: ["id", "code", "name", "display_name"],
				},
				{
					model: dbSAPPS.BudgetDepartment,
					as: "budgetdepartment",
					attributes: ["id", "name", "department_name"],
				},
				{
					model: dbSAPPS.User,
					as: "modifier",
					attributes: ["full_name"],
				},
			],
		});

		budgetClassifications = budgetClassifications.map((budgetClassification) => {
			return {
				...budgetClassification.dataValues,
				company_name: budgetClassification?.company?.display_name,
				budgetcategory_name: budgetClassification?.budgetcategory?.name,
				budgetdepartment_name: budgetClassification?.budgetdepartment?.name,
				modifier: budgetClassification?.modifier?.full_name,
			};
		});

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

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

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

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

		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 = {};

		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.id = {
				[Op.eq]: params.budgetclassification_id,
			};
		}

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

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

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

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

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

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

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