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

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

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

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

/**
 * Get all respiratoryRates with their respective companies.
 * @param {Object} params - An object that contains parameters to filter the respiratoryRates.
 * @param {Array} params.companiesId - Array of company IDs to filter by.
 * @returns {Promise<Object>} Resolves with an object that contains the respiratoryRates 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 respiratoryRates = [];
        respiratoryRates = await dbSAPPS.RespiratoryRate.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [
                {
                    model: dbSAPPS.Company,
                    as: 'company',
                    attributes: ['id', 'display_name']
                }
            ]
        });

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

        respiratoryRates = await formatWithModifier(respiratoryRates);

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

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

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

        let options = [];
        options = await dbSAPPS.RespiratoryRate.findAll({
            where: filterConditions,
            attributes: ['id', 'name', 'display_name'],
            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 respiratoryRates
 * 
 * @returns {Promise<{
 *   count: number,
 *   success: boolean,
 *   message: string
 * }>} 
 */
async function count(params) {
    try {
        // filter
        const filterConditions = {};

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

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

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

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

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

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

        // save
        await respiratoryRate.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 respiratoryRate
 * @param {number} id - the id of the respiratoryRate
 * @param {object} params - the update data
 * @param {boolean} params.enabled - the enabled status of the respiratoryRate
 * @param {number} [params.modified_by] - the modified by of the respiratoryRate
 * @param {Date} [params.modified] - the modified of the respiratoryRate
 * @returns {Promise<object>} - the result of the update
 */
async function enabled(id, params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        // validate existing
        const respiratoryRate = await dbSAPPS.RespiratoryRate.findByPk(id);
        if (!respiratoryRate) 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 respiratoryRate.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 respiratoryRate
 * @param {number} id - the id of the respiratoryRate
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        // validate existing
        const respiratoryRate = await dbSAPPS.RespiratoryRate.findByPk(id, { transaction });
        if (!respiratoryRate) return { success: false, message: 'ID not found!' };

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