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

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

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

		if (params.account_id) {
			filterConditions.id = {
				[Op.eq]: params.account_id,
			};
		}

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

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

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

		let accounts = [];
		accounts = await dbSAPPS.Account.findAll({
			where: filterConditions,
			include: [
				{
					model: dbSAPPS.Account,
					as: "parent",
					attributes: ["name"],
				},
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
				{
					model: dbSAPPS.User,
					as: "modifier",
					attributes: ["full_name"], // ambil field yang diperlukan
				},
			],
			order: [["modified", "DESC"]],
		});

		// update relation with name
		accounts = accounts.map((account) => {
			return {
				...account.dataValues,
				parent_account_name: account?.parent?.name,
				company_name: account?.company?.display_name,
				modifier: account?.modifier?.full_name,
			};
		});

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

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

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

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

		if (params.is_group) {
			filterConditions.is_group = {
				// true is always sent as a string from the frontend
				[Op.eq]: params.is_group,
			};
		}

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

		let options = [];
		options = await dbSAPPS.Account.findAll({
			attributes: [
				"id",
				"name",
				"account_name",
				"account_number",
				"is_group",
				"parent_account",
				"root_type",
				"report_type",
				"account_type",
				"account_currency",
				"company_id",
			],
			where: filterConditions,
			include: [
				{
					model: dbSAPPS.Account,
					as: "parent",
					attributes: ["name"],
				},
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "name", "display_name"],
				},
			],
			order: [["modified", "DESC"]],
		});

		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.disabled = {
			[Op.eq]: false,
		};

		const count = await dbSAPPS.Account.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 existing = await dbSAPPS.Account.findOne({
			where: {
				name: params.name,
				account_name: params.account_name,
				account_number: params.account_number,
				parent_account: params.parent_account,
				company_id: params.company_id,
			},
			transaction,
		});
		if (existing) {
			return {
				success: false,
				message: `is already taken.`,
			};
		}

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

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

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

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

		params.disabled = params.enabled;

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

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

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