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

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

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

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

/**
 * Get all trackingLocations with their respective companies.
 * @param {Object} params - An object that contains parameters to filter the trackingLocations.
 * @param {Array} params.companiesId - Array of company IDs to filter by.
 * @returns {Promise<Object>} Resolves with an object that contains the trackingLocations and a success flag.
 * @example
 * const result = await getAll({ companiesId: [1, 2] });
 * console.log(result);
 */
async function getAll(params) {
	try {
		// filter
		const filterConditions = {};

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

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

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

		trackingLocations = await formatWithModifier(trackingLocations);

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

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

		let options = [];
		options = await dbSAPPS.TrackingLocation.findAll({
			where: filterConditions,
			attributes: [
				"id",
				"user_id",
				"emplpoye_id",
				"company_id",
				"latitude",
				"longitude",
				"browser_name",
				"browser_version",
				"platform",
				"user_agent",
				"device_type",
				"ip_address",
				"battery_level",
				"battery_charging",
				"device_id",
			],
			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 trackingLocations
 *
 * @returns {Promise<{
 *   count: number,
 *   success: boolean,
 *   message: string
 * }>}
 */
async function count(params) {
	try {
		// filter
		const filterConditions = {};

		const count = await dbSAPPS.TrackingLocation.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 trackingLocation
 *
 * @param {object} params - trackingLocation data to be created.
 * @param {string} params.name - trackingLocation name.
 * @param {string} params.display_name - trackingLocation display name.
 * @param {number} [params.creation=Date.now()] - trackingLocation creation timestamp.
 * @param {number} [params.modified=Date.now()] - trackingLocation last modification timestamp.
 * @param {number} [params.owner=1] - User ID of the trackingLocation owner.
 * @param {number} [params.modified_by=1] - User ID of the last modifier of the trackingLocation.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the trackingLocation creation process.
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// save
		await dbSAPPS.TrackingLocation.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 trackingLocation
 *
 * @param {number} id - trackingLocation ID to be updated.
 * @param {object} params - trackingLocation data to be updated.
 * @param {string} [params.name] - trackingLocation name.
 * @param {string} [params.display_name] - trackingLocation display name.
 * @param {number} [params.creation] - trackingLocation creation timestamp.
 * @param {number} [params.modified] - trackingLocation last modification timestamp.
 * @param {number} [params.owner] - User ID of the trackingLocation owner.
 * @param {number} [params.modified_by] - User ID of the last modifier of the trackingLocation.
 *
 * @returns {Promise<{success: boolean, message: string}>} Result of the trackingLocation update process.
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// save
		await trackingLocation.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,
		};
	}
}

/**
 * Delete a trackingLocation
 * @param {number} id - the id of the trackingLocation
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const trackingLocation = await dbSAPPS.TrackingLocation.findByPk(id, {
			transaction,
		});
		if (!trackingLocation) return { success: false, message: "ID not found!" };

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