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

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

/**
 * Get all nationalities with their respective companies.
 * @param {Object} params - An object that contains parameters to filter the nationalities.
 * @param {Array} params.companiesId - Array of company IDs to filter by.
 * @returns {Promise<Object>} Resolves with an object that contains the nationalities 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 = [];

		// Company filtering/scoping
		// precedence: company_id wins over companiesId
		if (params?.company_id != null && String(params.company_id).trim() !== "") {
			const companyId = Number(params.company_id);
			if (!Number.isNaN(companyId)) {
				filterConditions.company_id = { [Op.eq]: companyId };
			}
		} else if (params?.companiesId != null) {
			const rawCompaniesId = params.companiesId;
			let companiesId = [];

			if (Array.isArray(rawCompaniesId)) {
				companiesId = rawCompaniesId;
			} else if (typeof rawCompaniesId === "string") {
				companiesId = rawCompaniesId.split(",");
			} else if (typeof rawCompaniesId === "number") {
				companiesId = [rawCompaniesId];
			}

			const parsedCompaniesId = companiesId.map((v) => Number(String(v).trim())).filter((v) => !Number.isNaN(v));

			if (parsedCompaniesId.length) {
				filterConditions.company_id = { [Op.in]: parsedCompaniesId };
			}
		}

		// Global search (q) + column filters (f_*)
		const q = typeof params?.q === "string" ? params.q.trim() : "";
		if (q) {
			andConditions.push({
				[Op.or]: [{ name: { [Op.like]: `%${q}%` } }, { display_name: { [Op.like]: `%${q}%` } }, { "$company.display_name$": { [Op.like]: `%${q}%` } }],
			});
		}

		const fName = typeof params?.f_name === "string" ? params.f_name.trim() : "";
		if (fName) andConditions.push({ name: { [Op.like]: `%${fName}%` } });

		const fDisplayName = typeof params?.f_display_name === "string" ? params.f_display_name.trim() : "";
		if (fDisplayName) andConditions.push({ display_name: { [Op.like]: `%${fDisplayName}%` } });

		const fCompanyName = typeof params?.f_company_name === "string" ? params.f_company_name.trim() : "";
		if (fCompanyName) andConditions.push({ "$company.display_name$": { [Op.like]: `%${fCompanyName}%` } });

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

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

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

		nationalities = await formatWithModifier(nationalities);

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

/**
 * Get nationalities with their respective settings.
 * @param {Object} params - An object that contains parameters to filter the nationalities.
 * @param {Array} params.companiesId - Array of company IDs to filter by.
 * @returns {Promise<Object>} Resolves with an object that contains the nationalities 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.company_id) {
			filterConditions.company_id = {
				[Op.eq]: params.company_id,
			};
		}

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

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

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

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

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

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

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