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

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

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

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

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_code) {
			filterConditions.code = {
				[Op.iLike]: `%${params.f_code}%`,
			};
		}

		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}%` } },
					{ code: { [Op.iLike]: `%${params.q}%` } },
					{ "$company.display_name$": { [Op.iLike]: `%${params.q}%` } },
				],
			});
		}

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

		// robust pagination defaults (mirroring callPlans/releaseNotes pattern)
		const rawSize = parseInt(params?.pageSize, 10);
		const pageSize = Number.isFinite(rawSize) && rawSize > 0 ? Math.min(rawSize, 100) : 10;
		const rawIndex = parseInt(params?.pageIndex, 10);
		const pageIndex = Number.isFinite(rawIndex) && rawIndex >= 0 ? rawIndex : 0;

		// optional whitelist for sorting (safe defaults)
		const allowedSortBy = ["modified", "display_name", "code", "name"];
		const sortBy = allowedSortBy.includes(params?.sortBy) ? params.sortBy : "modified";
		const sortDir = (params?.sortDir || "DESC").toString().toUpperCase() === "ASC" ? "ASC" : "DESC";

		const { rows, count } = await dbSAPPS.Department.findAndCountAll({
			where: whereClause,
			order: [[sortBy, sortDir]],
			offset: pageIndex * pageSize,
			limit: pageSize,
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name", "name"],
				},
				{
					model: dbSAPPS.Department,
					as: "parent",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.User,
					as: "modifier",
					attributes: ["full_name"],
				},
			],
		});

		let departments = rows;
		departments = departments.map((department) => {
			return {
				...department.dataValues,
				company_name: department?.company?.display_name,
				modifier: department?.modifier?.full_name,
				parent_name: department?.parent?.display_name,
			};
		});

		return {
			departments,
			// pagination meta for frontend (optional but useful)
			totalCount: count,
			pageIndex,
			pageSize,
			sortBy,
			sortDir,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error?.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

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

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

		if (params.is_parent) {
			filterConditions.is_parent = {
				// true is always sent as a string from the frontend
				[Op.eq]: params.is_parent === "true" || params.is_parent === true ? true : false,
			};
		}

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

		let options = [];
		options = await dbSAPPS.Department.findAll({
			attributes: ["id", "display_name", "slug_name", "code", "company_id"],
			where: filterConditions,
			order: [["name", "ASC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name", "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 departments
 *
 * @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.Department.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 department
 *
 * @param {object} params - department data to be created.
 * @param {string} params.name - department name.
 * @param {string} params.display_name - department display name.
 * @param {boolean} [params.enabled=true] - department enabled status.
 * @param {number} [params.creation=Date.now()] - department creation timestamp.
 * @param {number} [params.modified=Date.now()] - department last modification timestamp.
 * @param {number} [params.owner=1] - User ID of the department owner.
 * @param {number} [params.modified_by=1] - User ID of the last modifier of the department.
 *
 * @returns {Promise<object>} - the result of the delete
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existing = await dbSAPPS.Department.findOne({
			where: {
				display_name: params.display_name,
				name: params.name,
				company_id: params.company_id,
			},
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		if (!params.enabled) params.enabled = true;

		// save
		await dbSAPPS.Department.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 department
 *
 * @param {number} id - department ID to be updated.
 * @param {object} params - department data to be updated.
 * @param {string} [params.name] - department name.
 * @param {string} [params.display_name] - department display name.
 * @param {boolean} [params.enabled] - department enabled status.
 * @param {number} [params.modified=Date.now()] - department last modification timestamp.
 * @param {number} [params.modified_by] - User ID of the last modifier of the department.
 *
 * @returns {Promise<object>} - the result of the delete
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const department = await dbSAPPS.Department.findByPk(id);
		if (!department) return { success: false, message: "ID not found!" };

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

		// save
		await department.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 department
 *
 * @param {number} id - department ID to be updated.
 * @param {object} params - department data to be updated.
 * @param {boolean} params.enabled - department enabled status.
 * @param {number} [params.modified_by] - User ID of the last modifier of the department.
 * @param {number} [params.modified=Date.now()] - department last modification timestamp.
 *
 * @returns {Promise<object>} - the result of the delete
 */
async function enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const department = await dbSAPPS.Department.findByPk(id);
		if (!department) 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 department.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,
		};
	}
}

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

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