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 dosages by appending a modifier field to each company.
 */
const formatWithModifier = async (dosages) => {
    return Promise.all(
        dosages.map(async (dosage) => {
            const modifier = await dbSAPPS.User.findOne({
                where: {
                    id: dosage.modified_by
                },
                attributes: ['full_name']
            });

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

/**
 * Retrieves all dosages with their parent dosage title.
 * @param {Object} params - The query parameters.
 * @param {number[]} params.dosagesId - The ids of the dosages to retrieve.
 * @returns {Promise<Object>} - The response object with the dosages and success status.
 */
async function getAll(params) {
    try {
        // filters
        const filterConditions = {};

        let dosages = []
        dosages = await dbSAPPS.Dosage.findAll({
            order: [['modified', 'DESC']],
        });

        dosages = await formatWithModifier(dosages);

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

/**
 * Get dosage items with their respective settings.
 */
async function option(params) {
    try {
        // filter
        const filterConditions = {};

        let options = [];
        options = await dbSAPPS.Dosage.findAll({
            attributes: ['id', 'name', 'display_name'],
            where: filterConditions,
            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 dosage items
 * 
 */

async function count(params) {
    try {
        // filter
        const filterConditions = {};

        const count = await dbSAPPS.Dosage.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 dosage item.
 * 
 * @param {Object} params - The new dosage item data.
 * @param {string} params.name - The name of the dosage item.
 * @param {string} params.title - The title of the dosage item.
 * @param {number} [params.parent_id] - The ID of the parent dosage item.
 * @param {string} [params.url] - The URL of the dosage item.
 * @param {string} [params.icon] - The icon of the dosage item.
 * @param {string} [params.type=link] - The type of the dosage item (link, group, collapse, separator).
 * @param {boolean} [params.enabled=true] - Whether the dosage item is enabled.
 * @param {number} [params.creation=Date.now()] - The creation timestamp of the dosage item.
 * @param {number} [params.modified=Date.now()] - The last modification timestamp of the dosage item.
 * @param {number} [params.owner=1] - The ID of the user who created the dosage item.
 * @param {number} [params.modified_by=1] - The ID of the user who last modified the dosage item.
 * 
 * @returns {Promise<{success: boolean, message: string}>} Result of the dosage item creation process.
 */
async function create(params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        // validate existing

        // save
        await dbSAPPS.Dosage.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 dosage item.
 * 
 * @param {number} id - The ID of the dosage item to update.
 * @param {Object} params - The updated dosage item data.
 * @param {string} [params.name] - The new name of the dosage item.
 * @param {string} [params.title] - The new title of the dosage item.
 * @param {number} [params.parent_id] - The new parent ID of the dosage item.
 * @param {string} [params.url] - The new URL of the dosage item.
 * @param {string} [params.icon] - The new icon of the dosage item.
 * @param {string} [params.type] - The new type of the dosage item (link, group, collapse, separator).
 * @param {boolean} [params.enabled] - Whether the dosage item is enabled or not.
 * @param {number} [params.creation] - The new creation timestamp of the dosage item.
 * @param {number} [params.modified] - The new last modification timestamp of the dosage item.
 * @param {number} [params.owner] - The new ID of the user who created the dosage item.
 * @param {number} [params.modified_by] - The new ID of the user who last modified the dosage item.
 * 
 * @returns {Promise<{success: boolean, message: string}>} Result of the dosage item update process.
 */
async function update(id, params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        // validate existing
        const dosage = await dbSAPPS.Dosage.findByPk(id);
        if (!dosage) return { success: false, message: 'ID not found!' };

        // validate existing

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

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