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

// Choose case-insensitive operator when available (Postgres: ILIKE; others: LIKE)
const LikeOp = (() => {
	try {
		return dbSAPPS?.sequelize?.getDialect?.() === "postgres" ? Op.iLike : Op.like;
	} catch {
		return Op.like;
	}
})();

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

/**
 * Sync DesignationVersionChilds when master Designation is updated
 * Updates all designationversionchilds that reference this designation_id
 * @param {Number} designationId - The ID of the master designation
 * @param {Object} updatedDesignationData - The updated designation data
 * @param {Object} transaction - Sequelize transaction object
 * @returns {Promise<void>}
 */
async function syncDesignationVersionChildsOnMasterUpdate(designationId, updatedDesignationData, transaction) {
	try {
		// Find all designationversionchilds that reference this designation
		const designationVersionChilds = await dbSAPPS.DesignationVersionChild.findAll({
			where: { designation_id: designationId },
			transaction,
		});

		if (!designationVersionChilds || designationVersionChilds.length === 0) {
			return; // No childs to sync
		}

		// Fields to sync from master designation
		const fieldsToSync = ["name", "display_name", "slug_name", "code", "type", "is_parent", "description", "company_id"];

		// Prepare update data (only include fields that exist in updatedDesignationData)
		const updateData = {};
		fieldsToSync.forEach((field) => {
			if (updatedDesignationData[field] !== undefined && updatedDesignationData[field] !== null) {
				updateData[field] = updatedDesignationData[field];
			}
		});

		// Also update modified timestamp
		updateData.modified = Date.now();

		// Update all related designationversionchilds
		if (Object.keys(updateData).length > 0) {
			await dbSAPPS.DesignationVersionChild.update(updateData, {
				where: { designation_id: designationId },
				transaction,
			});
		}
	} catch (error) {
		console.error("Error syncing DesignationVersionChilds on master update:", error);
		// Re-throw to trigger transaction rollback and prevent inconsistent data
		throw error;
	}
}

/**
 * Delete DesignationVersionChilds when master Designation is deleted
 * Removes all designationversionchilds that reference this designation_id
 * @param {Number} designationId - The ID of the master designation
 * @param {Object} transaction - Sequelize transaction object
 * @returns {Promise<void>}
 */
async function deleteDesignationVersionChildsOnMasterDelete(designationId, transaction) {
	try {
		// Find all designationversionchilds that reference this designation
		const designationVersionChilds = await dbSAPPS.DesignationVersionChild.findAll({
			where: { designation_id: designationId },
			transaction,
		});

		if (!designationVersionChilds || designationVersionChilds.length === 0) {
			return; // No childs to delete
		}

		// Delete all related designationversionchilds
		await dbSAPPS.DesignationVersionChild.destroy({
			where: { designation_id: designationId },
			transaction,
		});
	} catch (error) {
		console.error("Error deleting DesignationVersionChilds on master delete:", error);
		// Re-throw to trigger transaction rollback and prevent orphaned data
		throw error;
	}
}

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

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

async function getAll(params) {
	try {
		const baseInclude = [
			{
				model: dbSAPPS.Designation,
				as: "parent",
				attributes: ["id", "display_name", "name"],
			},
			{
				model: dbSAPPS.Department,
				as: "department",
				attributes: ["id", "display_name", "name"],
			},
			{
				model: dbSAPPS.Company,
				as: "company",
				attributes: ["id", "display_name", "name"],
			},
		];

		// base filter conditions
		const filterConditions = {};

		// precedence: explicit company_id 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,
			};
		}

		// optional department filter
		if (params.department_id) {
			filterConditions.department_id = {
				[Op.eq]: params.department_id,
			};
		}

		// column-level filters
		if (params.f_display_name) {
			filterConditions.display_name = {
				[LikeOp]: `%${params.f_display_name}%`,
			};
		}

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

		if (params.f_department) {
			filterConditions["$department.display_name$"] = {
				[LikeOp]: `%${params.f_department}%`,
			};
		}

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

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

		// pagination & sorting (robust defaults)
		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;

		const allowedSortBy = ["modified", "display_name", "name", "code"];
		const sortBy = allowedSortBy.includes(params?.sortBy) ? params.sortBy : "modified";
		const sortDir = (params?.sortDir || "DESC").toString().toUpperCase() === "ASC" ? "ASC" : "DESC";

		const { rows, count } = await dbSAPPS.Designation.findAndCountAll({
			where: whereClause,
			order: [[sortBy, sortDir]],
			offset: pageIndex * pageSize,
			limit: pageSize,
			include: baseInclude,
		});

		// summary counts MUST reflect the same filters (server-side pagination)
		// use distinct to avoid inflated counts when includes are present
		const includeForCount = baseInclude.map((inc) => ({
			...inc,
			attributes: [],
			required: false,
		}));

		const [enabledCount, disabledCount] = await Promise.all([
			dbSAPPS.Designation.count({
				where: { ...whereClause, enabled: { [Op.eq]: true } },
				include: includeForCount,
				distinct: true,
				col: "id",
			}),
			dbSAPPS.Designation.count({
				where: { ...whereClause, enabled: { [Op.eq]: false } },
				include: includeForCount,
				distinct: true,
				col: "id",
			}),
		]);

		let designations = rows;
		designations = designations.map((designation) => {
			return {
				...designation.dataValues,
				company_name: designation?.company?.display_name,
				department_name: designation?.department?.display_name,
				parent_name: designation?.parent?.display_name,
			};
		});

		designations = await formatWithModifier(designations);

		return {
			designations,
			totalCount: count,
			summaryCounts: {
				total: count,
				enabled: enabledCount,
				disabled: disabledCount,
			},
			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 designations 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" ? true : false,
			};
		}

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

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

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

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

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

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

		// Get current designation data before update (for comparison)
		const currentDesignationData = {
			name: designation.name,
			display_name: designation.display_name,
			slug_name: designation.slug_name,
			code: designation.code,
			type: designation.type,
			is_parent: designation.is_parent,
			description: designation.description,
			company_id: designation.company_id,
		};

		// Update master designation
		await designation.update(params, { transaction });

		// Check if any syncable fields have changed
		const fieldsToSync = ["name", "display_name", "slug_name", "code", "type", "is_parent", "description", "company_id"];
		const hasChanges = fieldsToSync.some((field) => params[field] !== undefined && params[field] !== null && params[field] !== currentDesignationData[field]);

		// Sync designationversionchilds if there are changes to syncable fields
		if (hasChanges) {
			// Merge current data with updated params for complete sync
			const syncData = { ...currentDesignationData, ...params };
			await syncDesignationVersionChildsOnMasterUpdate(id, syncData, 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 designation
 *
 * @param {number} id - Designation ID to be updated.
 * @param {object} params - Designation data to be updated.
 * @param {boolean} params.enabled - Designation enabled status.
 * @param {number} [params.modified_by] - User ID of the last modifier of the designation.
 * @param {number} [params.modified=Date.now()] - Designation last modification timestamp.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the designation update process.
 */
async function enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const designation = await dbSAPPS.Designation.findByPk(id);
		if (!designation) 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 designation.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 designation
 * @param {number} id - ID of the designation 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 designation = await dbSAPPS.Designation.findByPk(id, { transaction });
		if (!designation) return { success: false, message: "ID not found!" };

		// Delete all related designationversionchilds first
		await deleteDesignationVersionChildsOnMasterDelete(id, transaction);

		// Then delete the master designation
		await designation.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,
		};
	}
}
