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

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

		budgetUnitOfMeasurements = budgetUnitOfMeasurements.map((budgetUnitOfMeasurement) => {
			return {
				...budgetUnitOfMeasurement.dataValues,
				company_name: budgetUnitOfMeasurement?.company?.display_name,
				modifier: budgetUnitOfMeasurement?.modifier?.full_name,
			};
		});

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

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

		let options = [];
		options = await dbSAPPS.BudgetUnitOfMeasurement.findAll({
			where: filterConditions,
			attributes: ["id", "name", "display_name", "code", "company_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.budgetunitofmeasurement_id) {
			filterConditions.id = {
				[Op.eq]: params.budgetunitofmeasurement_id,
			};
		}

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

		const count = await dbSAPPS.BudgetUnitOfMeasurement.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.BudgetUnitOfMeasurement.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 budgetUnitOfMeasurement = await dbSAPPS.BudgetUnitOfMeasurement.create(params, { transaction });

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

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

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