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

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

const formatWithModifier = async (upCountries) => {
	return Promise.all(
		upCountries.map(async (upCountry) => {
			const modifier = await dbSAPPS.User.findOne({
				where: {
					id: upCountry.modified_by,
				},
				attributes: ["full_name"],
			});

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

/**
 * Get all
 */
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,
			};
		}

		if (params.role_id) {
			filterConditions.id = {
				[Op.eq]: params.role_id,
			};
		}

		// 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 roles = [];
		roles = await dbSAPPS.Role.findAll({
			where: whereClause,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name"],
				},
			],
		});

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

		roles = await formatWithModifier(roles);

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

/**
 * Get options
 */
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,
			};
		}

		if (params.role_id) {
			filterConditions.id = {
				[Op.eq]: params.role_id,
			};
		}

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

		let options = [];
		options = await dbSAPPS.Role.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
 */
async function count(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,
			};
		}

		if (params.role_id) {
			filterConditions.id = {
				[Op.eq]: params.role_id,
			};
		}

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

		const count = await dbSAPPS.Role.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
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existingName = await dbSAPPS.Role.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.Role.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
		const role = await dbSAPPS.Role.create(params, { transaction });

		await transaction.commit();
		return {
			id: role?.id,
			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
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const role = await dbSAPPS.Role.findByPk(id);
		if (!role) return { success: false, message: "ID not found!" };

		// validate existing
		const existingName = await dbSAPPS.Role.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.Role.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.`,
			};
		}

		// whitelist fields to update (exclude company object, modifier, etc.)
		const ALLOWED_UPDATE_FIELDS = [
			"name",
			"display_name",
			"description",
			"company_id",
			"enabled",
			"modified",
			"modified_by",
			"access_read_all_data",
			"administrator_of_hr",
			"administrator_of_msd",
			"administrator_of_pirlo",
			"administrator_of_qmr",
			"administrator_of_fat",
			"administrator_of_health",
		];
		const updateData = {};
		for (const key of ALLOWED_UPDATE_FIELDS) {
			if (params[key] !== undefined) {
				updateData[key] = params[key];
			}
		}

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

/**
 * Enable or disable
 */
async function enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const role = await dbSAPPS.Role.findByPk(id);
		if (!role) 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 role.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
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const role = await dbSAPPS.Role.findByPk(id, { transaction });
		if (!role) return { success: false, message: "ID not found!" };

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