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 (placementAreas) => {
	return Promise.all(
		placementAreas.map(async (placementArea) => {
			const modifier = await dbSAPPS.User.findOne({
				where: { id: placementArea.modified_by },
				attributes: ["full_name"],
			});
			return {
				...placementArea,
				modifier: modifier?.full_name,
			};
		})
	);
};

async function getAll(params) {
	try {
		const filterConditions = {};

		if (params.companiesId && params.companiesId.length) {
			// ROBUST: Include NULL company_id (global/shared data) when filtering by companies
			filterConditions[Op.or] = [
				{ company_id: { [Op.in]: params.companiesId } },
				{ company_id: null }
			];
		}

		if (params.is_primary !== undefined) {
			filterConditions.is_primary = params.is_primary;
		}

		let placementAreas = [];
		placementAreas = await dbSAPPS.PlacementArea.findAll({
			where: filterConditions,
			order: [["is_primary", "DESC"], ["display_name", "ASC"]],
			include: [
				{ model: dbSAPPS.Company, as: "company", attributes: ["id", "display_name"] },
				{ model: dbSAPPS.City, as: "city", attributes: ["id", "display_name"] },
				{ model: dbSAPPS.PlacementArea, as: "parent", attributes: ["id", "display_name"] },
			],
		});

		placementAreas = placementAreas.map((pa) => ({
			...pa.dataValues,
			company_name: pa?.company?.display_name,
			city_name: pa?.city?.display_name,
			parent_name: pa?.parent?.display_name,
		}));

		placementAreas = await formatWithModifier(placementAreas);

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

async function option(params) {
	try {
		const filterConditions = { enabled: { [Op.eq]: true } };

		if (params.company_id) {
			filterConditions.company_id = { [Op.eq]: params.company_id };
		}

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

		if (params.is_primary !== undefined) {
			filterConditions.is_primary = params.is_primary;
		}

		let options = await dbSAPPS.PlacementArea.findAll({
			where: filterConditions,
			attributes: ["id", "name", "display_name", "is_primary", "parent_id", "city_id"],
			include: [
				{ model: dbSAPPS.Company, as: "company", attributes: ["id", "display_name"] },
				{ model: dbSAPPS.City, as: "city", attributes: ["id", "display_name"] },
			],
			order: [["is_primary", "DESC"], ["display_name", "ASC"]],
		});

		options = options.map((o) => ({
			...o.dataValues,
			company_name: o?.company?.display_name,
			city_name: o?.city?.display_name,
		}));

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

async function count(params) {
	try {
		const filterConditions = { enabled: { [Op.eq]: true } };
		const count = await dbSAPPS.PlacementArea.count({ where: filterConditions });
		return { count, success: true, message: "Loaded successfully!" };
	} catch (error) {
		return { success: false, message: error?.message || "Failed to load, please try again!" };
	}
}

async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		const existingName = await dbSAPPS.PlacementArea.findOne({
			where: { name: params.name, company_id: params.company_id || null },
			transaction,
		});
		if (existingName) {
			return { success: false, message: `"${params.name}" is already taken.` };
		}

		const existingDisplayName = await dbSAPPS.PlacementArea.findOne({
			where: {
				display_name: params.display_name,
				company_id: params.company_id || null,
			},
			transaction,
		});
		if (existingDisplayName) {
			return { success: false, message: `"${params.display_name}" is already taken.` };
		}

		await dbSAPPS.PlacementArea.create(params, { transaction });
		await transaction.commit();
		return { success: true, message: "Saved successfully!" };
	} catch (error) {
		await transaction.rollback();
		return { success: false, message: error?.message || "Failed to save, please try again!" };
	}
}

async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		const placementArea = await dbSAPPS.PlacementArea.findByPk(id);
		if (!placementArea) return { success: false, message: "ID not found!" };

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

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

		await placementArea.update(params, { transaction });
		await transaction.commit();
		return { success: true, message: "Saved successfully!" };
	} catch (error) {
		await transaction.rollback();
		return { success: false, message: error?.message || "Failed to save, please try again!" };
	}
}

async function enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		const placementArea = await dbSAPPS.PlacementArea.findByPk(id);
		if (!placementArea) return { success: false, message: "ID not found!" };

		const updateData = { enabled: params.enabled };
		if (params.modified_by) updateData.modified_by = params.modified_by;
		if (params.modified) updateData.modified = params.modified;

		await placementArea.update(updateData, { transaction });
		await transaction.commit();
		return { success: true, message: "Saved successfully!" };
	} catch (error) {
		await transaction.rollback();
		return { success: false, message: error?.message || "Failed to save, please try again!" };
	}
}

async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		const placementArea = await dbSAPPS.PlacementArea.findByPk(id, { transaction });
		if (!placementArea) return { success: false, message: "ID not found!" };

		const employeeCount = await dbSAPPS.Employee.count({
			where: {
				[Op.or]: [
					{ placement_area_id: id },
					{ secondary_placement_area_id: id },
				],
			},
			transaction,
		});
		if (employeeCount > 0) {
			return {
				success: false,
				message: `Cannot delete. This placement area is used by ${employeeCount} employee(s).`,
			};
		}

		await placementArea.destroy({ transaction });
		await transaction.commit();
		return { success: true, message: "Deleted successfully!" };
	} catch (error) {
		await transaction.rollback();
		return { success: false, message: error?.message || "Failed to delete, please try again!" };
	}
}
