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

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

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

		budgetApprovers = budgetApprovers.map((budgetApprover) => {
			return {
				...budgetApprover.dataValues,
				company_name: budgetApprover?.company?.display_name,
				budgetapprover_name: budgetApprover?.ba_full_name + " - " + budgetApprover?.ba_designation_name,
				financeapprover_name: budgetApprover?.fin_full_name + " - " + budgetApprover?.fin_designation_name,
				budgetdepartment_name: budgetApprover?.budgetdepartment?.name,
				modifier: budgetApprover?.modifier?.full_name,
			};
		});

		return {
			budgetApprovers,
			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,
			};
		}

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

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

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

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

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

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

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

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

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

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

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