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 budgetAccounts = [];
		budgetAccounts = await dbSAPPS.BudgetAccount.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.Account,
					as: "account",
					attributes: ["id", "name", "account_name"],
				},
				{
					model: dbSAPPS.User,
					as: "modifier",
					attributes: ["full_name"],
				},
			],
		});

		budgetAccounts = budgetAccounts.map((budgetAccount) => {
			return {
				...budgetAccount.dataValues,
				company_name: budgetAccount?.company?.display_name,
				budgetdepartment_name: budgetAccount?.budgetdepartment?.name,
				account_name: budgetAccount?.account?.name,
				modifier: budgetAccount?.modifier?.full_name,
			};
		});

		return {
			budgetAccounts,
			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.BudgetAccount.findAll({
			where: filterConditions,
			attributes: ["id", "name", "company_id", "budgetdepartment_id", "account_id"],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name", "abbr"],
				},
				{
					model: dbSAPPS.BudgetDepartment,
					as: "budgetdepartment",
					attributes: ["id", "name", "department_name"],
				},
				{
					model: dbSAPPS.Account,
					as: "account",
					attributes: ["id", "name", "account_name"],
				},
			],
			order: [["name", "ASC"]],
		});

		options = options.map((option) => {
			return {
				...option.dataValues,
				company_name: option?.company?.display_name,
				budgetdepartment_name: option?.budgetdepartment?.name,
				account_name: option?.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.budgetdepartment_id) {
			filterConditions.budgetdepartment_id = {
				[Op.eq]: params.budgetdepartment_id,
			};
		}

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

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

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

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

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

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