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

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

/**
 * Format an array of banks by appending a modifier field to each company.
 * The modifier field is the full name of the user who last modified the company.
 * @param {Object[]} banks - The array of banks to format.
 * @returns {Promise<Object[]>} - The formatted array of banks.
 */
const formatWithModifier = async (banks) => {
	return Promise.all(
		banks.map(async (bank) => {
			const modifier = await dbSAPPS.User.findOne({
				where: {
					id: bank.modified_by,
				},
				attributes: ["full_name"],
			});

			return {
				...bank,
				modifier: modifier?.full_name,
			};
		}),
	);
};

/**
 * Get all banks with their respective companies.
 * @param {Object} params - An object that contains parameters to filter the banks.
 * @param {Array} params.companiesId - Array of company IDs to filter by.
 * @returns {Promise<Object>} Resolves with an object that contains the banks and a success flag.
 * @example
 * const result = await getAll({ companiesId: [1, 2] });
 * console.log(result);
 */
async function getAll(params) {
	try {
		// filter
		const filterConditions = {};

		const andConditions = [];
		const safeParams = params && typeof params === "object" ? params : {};

		// column filters
		if (safeParams.f_name && String(safeParams.f_name).trim().length > 0) {
			andConditions.push({ name: { [Op.like]: `%${String(safeParams.f_name).trim()}%` } });
		}
		if (safeParams.f_display_name && String(safeParams.f_display_name).trim().length > 0) {
			andConditions.push({ display_name: { [Op.like]: `%${String(safeParams.f_display_name).trim()}%` } });
		}
		if (safeParams.f_code && String(safeParams.f_code).trim().length > 0) {
			andConditions.push({ code: { [Op.like]: `%${String(safeParams.f_code).trim()}%` } });
		}

		// global search
		if (safeParams.q && String(safeParams.q).trim().length > 0) {
			const q = String(safeParams.q).trim();
			andConditions.push({
				[Op.or]: [{ name: { [Op.like]: `%${q}%` } }, { display_name: { [Op.like]: `%${q}%` } }, { code: { [Op.like]: `%${q}%` } }],
			});
		}

		if (andConditions.length > 0) {
			filterConditions[Op.and] = andConditions;
		}

		let banks = [];
		banks = await dbSAPPS.Bank.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
		});

		banks = banks.map((bank) => {
			return {
				...bank.dataValues,
			};
		});

		banks = await formatWithModifier(banks);

		return {
			banks,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error?.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Get banks with their respective settings.
 * @param {Object} params - An object that contains parameters to filter the banks.
 * @param {Array} params.companiesId - Array of company IDs to filter by.
 * @returns {Promise<Object>} Resolves with an object that contains the banks and a success flag.
 * @example
 * const result = await option({ companiesId: [1, 2] });
 * console.log(result);
 */
async function option(params) {
	try {
		// filter
		const filterConditions = {};

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

		let options = [];
		options = await dbSAPPS.Bank.findAll({
			where: filterConditions,
			attributes: ["id", "name", "display_name", "code"],
			order: [["name", "ASC"]],
		});

		options = options.map((option) => {
			return {
				...option.dataValues,
			};
		});

		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 active banks
 *
 * @returns {Promise<{
 *   count: number,
 *   success: boolean,
 *   message: string
 * }>}
 */
async function count(params) {
	try {
		// filter
		const filterConditions = {};

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

		const count = await dbSAPPS.Bank.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 bank
 *
 * @param {object} params - bank data to be created.
 * @param {string} params.name - bank name.
 * @param {string} params.display_name - bank display name.
 * @param {boolean} [params.enabled=true] - bank enabled status.
 * @param {number} [params.creation=Date.now()] - bank creation timestamp.
 * @param {number} [params.modified=Date.now()] - bank last modification timestamp.
 * @param {number} [params.owner=1] - User ID of the bank owner.
 * @param {number} [params.modified_by=1] - User ID of the last modifier of the bank.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the bank creation process.
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existingName = await dbSAPPS.Bank.findOne({
			where: { name: params.name },
			transaction,
		});
		if (existingName) {
			return {
				success: false,
				message: `"${params.name}" is already taken.`,
			};
		}

		const existingDisplayName = await dbSAPPS.Bank.findOne({
			where: { display_name: params.display_name },
			transaction,
		});
		if (existingDisplayName) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		const existingCode = await dbSAPPS.Bank.findOne({
			where: { code: params.code },
			transaction,
		});
		if (existingCode) {
			return {
				success: false,
				message: `"${params.code}" is already taken.`,
			};
		}

		// save
		await dbSAPPS.Bank.create(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,
		};
	}
}

/**
 * Updates an existing bank
 *
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const bank = await dbSAPPS.Bank.findByPk(id);
		if (!bank) return { success: false, message: "ID not found!" };

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

		const existingDisplayName = await dbSAPPS.Bank.findOne({
			where: {
				display_name: params.display_name,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existingDisplayName) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		const existingCode = await dbSAPPS.Bank.findOne({
			where: {
				code: params.code,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existingCode) {
			return {
				success: false,
				message: `"${params.code}" is already taken.`,
			};
		}

		// save
		await bank.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 a bank
 * @param {number} id - the id of the bank
 * @param {object} params - the update data
 * @param {boolean} params.enabled - the enabled status of the bank
 * @param {number} [params.modified_by] - the modified by of the bank
 * @param {Date} [params.modified] - the modified of the bank
 * @returns {Promise<object>} - the result of the update
 */
async function enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const bank = await dbSAPPS.Bank.findByPk(id);
		if (!bank) 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 bank.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 a bank
 * @param {number} id - the id of the bank
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const bank = await dbSAPPS.Bank.findByPk(id, { transaction });
		if (!bank) return { success: false, message: "ID not found!" };

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