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

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

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

        let medicalExaminations = [];
        medicalExaminations = await dbSAPPS.MedicalExamination.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: [{
                model: dbSAPPS.MedicalExaminationItem,
                as: 'medicalexaminationitems',
                attributes: ['id', 'medicalexamination_id', 'display_name', 'description'],
            }],
        });


        medicalExaminations = medicalExaminations.map(medicalExamination => {
            return {
                ...medicalExamination.dataValues
            }
        });

        medicalExaminations = await formatWithModifier(medicalExaminations);

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

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

        let options = [];
        options = await dbSAPPS.MedicalExamination.findAll({
            attributes: ['id', 'name', 'display_name'],
            where: filterConditions,
            order: [['name', 'DESC']],
            include: [{
                model: dbSAPPS.MedicalExaminationItem,
                as: 'medicalexaminationitems',
                attributes: ['id', 'medicalexamination_id', 'display_name', 'description'],
            }],
        });

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

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

        const count = await dbSAPPS.MedicalExamination.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
        };
    }
}

async function create(params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        // validate existing
        const existingDisplayName = await dbSAPPS.MedicalExamination.findOne({
            where: { display_name: params.display_name },
            transaction
        });
        if (existingDisplayName) {
            return {
                success: false,
                message: `"${params.display_name}" is already taken.`
            };
        }

        // If some fields do not have values, set default values
        if (!params.creation) params.creation = Date.now();
        if (!params.modified) params.modified = Date.now();
        if (!params.modified_by) params.modified_by = 1;  // Default if no value
        if (!params.owner) params.owner = 1;  // Default if no value

        // Create new
        const medicalExamination = await dbSAPPS.MedicalExamination.create(params, { transaction });

        // Ensure is a valid array
        const medicalexaminationitems = Array.isArray(params.medicalexaminationitems) ? params.medicalexaminationitems : [];

        // Loop through each item in the array and add it to the database
        if (medicalexaminationitems.length > 0) {
            await dbSAPPS.MedicalExaminationItem.bulkCreate(
                medicalexaminationitems.map(item => ({
                    ...item,
                    creation: params.creation,
                    modified: params.modified,
                    modified_by: params.modified_by,
                    owner: params.owner,
                    medicalexamination_id: medicalExamination.id
                })),
                { 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
        };
    }
}

async function update(id, params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        // validate existing
        const medicalExamination = await dbSAPPS.MedicalExamination.findByPk(id);
        if (!medicalExamination) return { success: false, message: 'ID not found!' };

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

        await medicalExamination.update(params, { transaction });

        // Delete existing
        await dbSAPPS.MedicalExaminationItem.destroy({ where: { medicalExamination_id: id }, transaction });

        // Ensure is a valid array
        const medicalexaminationitems = Array.isArray(params.medicalexaminationitems) ? params.medicalexaminationitems : [];

        // Loop through each item in the array and add it to the database
        if (medicalexaminationitems.length > 0) {
            await dbSAPPS.MedicalExaminationItem.bulkCreate(
                medicalexaminationitems.map(item => ({
                    ...item,
                    creation: params.creation,
                    modified: params.modified,
                    modified_by: params.modified_by,
                    medicalexamination_id: id
                })),
                { 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
        };
    }
}

async function _delete(id) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        // validate existing
        const medicalExamination = await dbSAPPS.MedicalExamination.findByPk(id);
        if (!medicalExamination) return { success: false, message: 'ID not found!' };

        // delete
        await medicalExamination.destroy({ transaction });

        // delete item
        await dbSAPPS.MedicalExaminationItem.destroy({ where: { medicalexamination_id: id }, 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
        };
    }
}
