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

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

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

        let drugs = [];
        drugs = await dbSAPPS.Drug.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
        });

        drugs = await formatWithModifier(drugs);

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

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

        let options = [];
        options = await dbSAPPS.Drug.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 active drugs
 * 
 * @returns {Promise<{
 *   count: number,
 *   success: boolean,
 *   message: string
 * }>} 
 */
async function count(params) {
    try {
        // filter
        const filterConditions = {};

        const count = await dbSAPPS.Drug.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 drug
 * 
 * @param {object} params - drug data to be created.
 * @param {string} params.name - drug name.
 * @param {string} params.display_name - drug display name.
 * @param {boolean} [params.enabled=true] - drug enabled status.
 * @param {number} [params.creation=Date.now()] - drug creation timestamp.
 * @param {number} [params.modified=Date.now()] - drug last modification timestamp.
 * @param {number} [params.owner=1] - User ID of the drug owner.
 * @param {number} [params.modified_by=1] - User ID of the last modifier of the drug.
 * 
 * @returns {Promise<{success: boolean, message: string}>} Result of the drug creation process.
 */
async function create(params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        // validate existing
        const existingDisplayName = await dbSAPPS.Drug.findOne({
            where: { display_name: params.display_name },
            transaction
        });
        if (existingDisplayName) {
            return {
                success: false,
                message: `"${params.display_name}" is already taken.`
            };
        }

        // save
        await dbSAPPS.Drug.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 drug
 * 
 * @param {number} id - drug ID to be updated.
 * @param {object} params - drug data to be updated.
 * @param {string} [params.name] - drug name.
 * @param {string} [params.display_name] - drug display name.
 * @param {boolean} [params.enabled] - drug enabled status.
 * @param {number} [params.creation] - drug creation timestamp.
 * @param {number} [params.modified] - drug last modification timestamp.
 * @param {number} [params.owner] - User ID of the drug owner.
 * @param {number} [params.modified_by] - User ID of the last modifier of the drug.
 * 
 * @returns {Promise<{success: boolean, message: string}>} Result of the drug update process.
 */
async function update(id, params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        // validate existing
        const drug = await dbSAPPS.Drug.findByPk(id);
        if (!drug) return { success: false, message: 'ID not found!' };

        // validate existing
        const existingDisplayName = await dbSAPPS.Drug.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 drug.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 drug
 * @param {number} id - the id of the drug
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        // validate existing
        const drug = await dbSAPPS.Drug.findByPk(id, { transaction });
        if (!drug) return { success: false, message: 'ID not found!' };

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