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

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

/**
 * Retrieve all
 */
async function getAll(params) {
	try {
		// base filters
		const filterConditions = {};

		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.doctype_id) {
			filterConditions.id = {
				[Op.eq]: params.doctype_id,
			};
		}

		// column filters
		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_modifier) {
			filterConditions["$modifier.full_name$"] = {
				[Op.iLike]: `%${params.f_modifier}%`,
			};
		}

		// global search q
		const andConditions = [];
		if (params.q) {
			andConditions.push({
				[Op.or]: [
					{ name: { [Op.iLike]: `%${params.q}%` } },
					{ display_name: { [Op.iLike]: `%${params.q}%` } },
					{ "$modifier.full_name$": { [Op.iLike]: `%${params.q}%` } },
				],
			});
		}

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

		let docTypes = [];
		docTypes = await dbSAPPS.DocType.findAll({
			where: whereClause,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.User,
					as: "modifier",
					attributes: ["full_name"],
				},
			],
		});

		docTypes = docTypes.map((doctype) => {
			return {
				...doctype.dataValues,
				modifier: doctype.modifier?.full_name,
			};
		});

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

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

		let options = [];
		options = await dbSAPPS.DocType.findAll({
			where: filterConditions,
			attributes: ["id", "name", "display_name"],
			order: [["name", "ASC"]],
		});

		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 = {};

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

		const count = await dbSAPPS.DocType.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.DocType.findOne({
			where: { name: params.name },
			transaction,
		});
		if (existingName) {
			return {
				success: false,
				message: `"${params.name}" is already taken.`,
			};
		}

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

		// save
		const docType = await dbSAPPS.DocType.create(params, { transaction });

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

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

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

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

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

		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 docType.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,
		};
	}
}

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

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