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

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

/**
 * Get all emailAccounts with their respective companies.
 */
async function getAll(params) {
	try {
		// filter
		const filterConditions = {};

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

		if (params.name) {
			filterConditions.name = {
				[Op.like]: `%${params.name}%`,
			};
		}

		let emailAccounts = [];
		emailAccounts = await dbSAPPS.EmailAccount.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name"],
				},
				{
					model: dbSAPPS.User,
					as: "modifier",
					attributes: ["full_name"],
				},
				{
					model: dbSAPPS.Email,
					as: "email",
					attributes: ["id", "name", "domain_name", "email_server"],
				},
			],
		});

		emailAccounts = emailAccounts.map((emailAccount) => {
			return {
				...emailAccount.dataValues,
				company_name: emailAccount?.company?.display_name,
				modifier: emailAccount?.modifier?.full_name,
				domain_name: emailAccount?.email?.domain_name,
				email_server: emailAccount?.email?.email_server,
			};
		});

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

/**
 * Get emailAccounts with their respective settings.
 */
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.EmailAccount.findAll({
			where: filterConditions,
			attributes: ["id", "name", "email_account"],
			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 emailAccounts
 */
async function count(params) {
	try {
		// filter
		const filterConditions = {};

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

		const count = await dbSAPPS.EmailAccount.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 emailAccount
 *
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existing = await dbSAPPS.EmailAccount.findOne({
			where: { name: params.name, email_account: params.email_account, company_id: params.company_id },
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `"${params.name}" is already taken.`,
			};
		}

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

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

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

/**
 * Enable or disable a emailAccount
 */
async function enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const emailAccount = await dbSAPPS.EmailAccount.findByPk(id);
		if (!emailAccount) 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 emailAccount.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 a emailAccount
 * @param {number} id - the id of the emailAccount
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const emailAccount = await dbSAPPS.EmailAccount.findByPk(id, { transaction });
		if (!emailAccount) return { success: false, message: "ID not found!" };

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

async function sendEmail(params) {
	try {
		// debug (avoid logging credentials)
		console.log("sendEmail", {
			to: params?.to,
			cc: params?.cc,
			subject: params?.subject,
			host: params?.value?.email?.smtp_server || params?.value?.email_server,
			port: params?.value?.email?.smtp_port || 465,
			secure: !!params?.value?.email?.use_ssl_for_outgoing,
		});

		const transporter = nodemailer.createTransport({
			host: params?.value?.email?.smtp_server || params?.value?.email_server,
			port: params?.value?.email?.smtp_port || 465,
			secure: params?.value?.email?.use_ssl_for_outgoing,
			auth: {
				user: params?.value?.email_account,
				pass: params?.value?.password,
			},
			connectionTimeout: 30_000,
			greetingTimeout: 30_000,
			socketTimeout: 30_000,
			tls: {
				rejectUnauthorized: false,
			},
		});

		const mailOptions = {
			from: params?.type === "applicant" ? `${params?.value?.fullname} <${params?.value?.email_user}>` : params?.value?.email_account,
			to: params.to,
			cc: params?.cc,

			subject: params?.subject,
			text: params?.text,
			html: params?.html,
		};

		const info = await transporter.sendMail(mailOptions);

		return {
			success: true,
			message: `Email sent: ${info.messageId}`,
		};
	} catch (error) {
		console.error("Error sending email:", error);
		return {
			success: false,
			message: `Failed to send email: ${error.message}`,
		};
	}
}
