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

		let zones = [];
		zones = await dbSAPPS.Zone.findAll({
			where: filterConditions,
			order: [["zone_order", "ASC"], ["modified", "DESC"]],
			include: [
				{ model: dbSAPPS.Company, as: "company", attributes: ["id", "display_name"] },
			],
		});

		zones = zones.map((zone) => ({
			...zone.dataValues,
			company_name: zone?.company?.display_name,
		}));

		zones = await formatWithModifier(zones);

		return {
			zones,
			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 };
		}

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

		options = options.map((o) => ({
			...o.dataValues,
			company_name: o?.company?.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.Zone.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.Zone.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.Zone.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.Zone.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 zone = await dbSAPPS.Zone.findByPk(id);
		if (!zone) return { success: false, message: "ID not found!" };

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

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

		await zone.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 zone = await dbSAPPS.Zone.findByPk(id);
		if (!zone) 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 zone.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 zone = await dbSAPPS.Zone.findByPk(id, { transaction });
		if (!zone) return { success: false, message: "ID not found!" };

		const employeeCount = await dbSAPPS.Employee.count({
			where: { zone_id: id },
			transaction,
		});
		if (employeeCount > 0) {
			return {
				success: false,
				message: `Cannot delete. This zone is used by ${employeeCount} employee(s).`,
			};
		}

		await zone.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!" };
	}
}
