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

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

/**
 * Format an array of branches 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[]} branches - The array of branches to format.
 * @returns {Promise<Object[]>} - The formatted array of branches.
 */
const formatWithModifier = async (branches) => {
	return Promise.all(
		branches.map(async (branch) => {
			const modifier = await dbSAPPS.User.findOne({
				where: {
					id: branch.modified_by,
				},
				attributes: ["full_name"],
			});

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

/**
 * Retrieves all branches with their parent branch title.
 * @param {Object} params - The query parameters.
 * @param {number[]} params.branchesId - The ids of the branches to retrieve.
 * @returns {Promise<Object>} - The response object with the branches and success status.
 */
async function getAll(params) {
	try {
		// base filter conditions
		const filterConditions = {};

		// precedence: explicit company_id from UI filter wins over companiesId scope
		if (params.company_id) {
			filterConditions.company_id = {
				[Op.eq]: params.company_id,
			};
		} else if (params.companiesId) {
			filterConditions.company_id = {
				[Op.in]: params.companiesId,
			};
		}

		// column-level filters from frontend (TableData.jsx)
		if (params.f_name) {
			filterConditions.name = {
				[Op.iLike]: `%${params.f_name}%`,
			};
		}

		if (params.f_display_name) {
			filterConditions.display_name = {
				[Op.iLike]: `%${params.f_display_name}%`,
			};
		}

		if (params.f_company) {
			filterConditions["$company.display_name$"] = {
				[Op.iLike]: `%${params.f_company}%`,
			};
		}

		// global search q across key fields
		const andConditions = [];
		if (params.q) {
			andConditions.push({
				[Op.or]: [
					{ name: { [Op.iLike]: `%${params.q}%` } },
					{ display_name: { [Op.iLike]: `%${params.q}%` } },
					{ "$company.display_name$": { [Op.iLike]: `%${params.q}%` } },
				],
			});
		}

		const whereClause = {
			...filterConditions,
			...(andConditions.length
				? {
						[Op.and]: andConditions,
					}
				: {}),
		};

		let branches = [];
		branches = await dbSAPPS.Branch.findAll({
			where: whereClause,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name"],
				},
			],
		});

		branches = branches.map((branch) => {
			return {
				...branch.dataValues,
				company_name: branch?.company?.display_name,
			};
		});

		branches = await formatWithModifier(branches);

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

/**
 * Get branch items with their respective settings.
 * @param {Object} params - An object that contains parameters to filter the branch items.
 * @param {boolean|string} params.is_parent - A boolean or string indicating whether the branch items should be parents or not.
 * @returns {Promise<Object>} Resolves with an object that contains the branch items and a success flag.
 * @example
 * const result = await option({ is_parent: true });
 * console.log(result);
 */
async function option(params) {
	try {
		// filter
		const filterConditions = {};

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

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

		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 active branch items
 *
 * @returns {Promise<{
 *   count: number,
 *   success: boolean,
 *   message: string
 * }>}
 */

async function count(params) {
	try {
		// filter
		const filterConditions = {};

		const count = await dbSAPPS.Branch.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 branch item.
 *
 * @param {Object} params - The new branch item data.
 * @param {string} params.name - The name of the branch item.
 * @param {string} params.title - The title of the branch item.
 * @param {number} [params.parent_id] - The ID of the parent branch item.
 * @param {string} [params.url] - The URL of the branch item.
 * @param {string} [params.icon] - The icon of the branch item.
 * @param {string} [params.type=link] - The type of the branch item (link, group, collapse, separator).
 * @param {boolean} [params.enabled=true] - Whether the branch item is enabled.
 * @param {number} [params.creation=Date.now()] - The creation timestamp of the branch item.
 * @param {number} [params.modified=Date.now()] - The last modification timestamp of the branch item.
 * @param {number} [params.owner=1] - The ID of the user who created the branch item.
 * @param {number} [params.modified_by=1] - The ID of the user who last modified the branch item.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the branch item creation process.
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existingDisplayName = await dbSAPPS.Branch.findOne({
			where: {
				name: params.name,
				display_name: params.display_name,
				company_id: params.company_id,
			},
			transaction,
		});
		if (existingDisplayName) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		// save
		await dbSAPPS.Branch.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 branch item.
 *
 * @param {number} id - The ID of the branch item to update.
 * @param {Object} params - The updated branch item data.
 * @param {string} [params.name] - The new name of the branch item.
 * @param {string} [params.title] - The new title of the branch item.
 * @param {number} [params.parent_id] - The new parent ID of the branch item.
 * @param {string} [params.url] - The new URL of the branch item.
 * @param {string} [params.icon] - The new icon of the branch item.
 * @param {string} [params.type] - The new type of the branch item (link, group, collapse, separator).
 * @param {boolean} [params.enabled] - Whether the branch item is enabled or not.
 * @param {number} [params.creation] - The new creation timestamp of the branch item.
 * @param {number} [params.modified] - The new last modification timestamp of the branch item.
 * @param {number} [params.owner] - The new ID of the user who created the branch item.
 * @param {number} [params.modified_by] - The new ID of the user who last modified the branch item.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the branch item update process.
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const branch = await dbSAPPS.Branch.findByPk(id);
		if (!branch) return { success: false, message: "ID not found!" };

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

		// save
		await branch.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,
		};
	}
}

/**
 * Delete a branch
 * @param {number} id - the id of the branch
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const branch = await dbSAPPS.Branch.findByPk(id);
		if (!branch) return { success: false, message: "ID not found!" };

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