
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Bowel_movementsDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const bowel_movements = await db.bowel_movements.create(
            {
                id: data.id || undefined,
        
        occurred_at: data.occurred_at
        ||
        null
            ,
            
        bristol_type: data.bristol_type
        ||
        null
            ,
            
        color: data.color
        ||
        null
            ,
            
        blood_present: data.blood_present
        ||
        false
        
            ,
            
        mucus_present: data.mucus_present
        ||
        false
        
            ,
            
        associated_symptoms: data.associated_symptoms
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bowel_movements.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return bowel_movements;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const bowel_movementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                occurred_at: item.occurred_at
            ||
            null
            ,
            
                bristol_type: item.bristol_type
            ||
            null
            ,
            
                color: item.color
            ||
            null
            ,
            
                blood_present: item.blood_present
            ||
            false
        
            ,
            
                mucus_present: item.mucus_present
            ||
            false
        
            ,
            
                associated_symptoms: item.associated_symptoms
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const bowel_movements = await db.bowel_movements.bulkCreate(bowel_movementsData, { transaction });

        // For each item created, replace relation files
        

        return bowel_movements;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const bowel_movements = await db.bowel_movements.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
        
        
        if (data.bristol_type !== undefined) updatePayload.bristol_type = data.bristol_type;
        
        
        if (data.color !== undefined) updatePayload.color = data.color;
        
        
        if (data.blood_present !== undefined) updatePayload.blood_present = data.blood_present;
        
        
        if (data.mucus_present !== undefined) updatePayload.mucus_present = data.mucus_present;
        
        
        if (data.associated_symptoms !== undefined) updatePayload.associated_symptoms = data.associated_symptoms;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

        await bowel_movements.update(updatePayload, {transaction});

        
        
        if (data.user !== undefined) {
            await bowel_movements.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return bowel_movements;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const bowel_movements = await db.bowel_movements.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of bowel_movements) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of bowel_movements) {
                await record.destroy({transaction});
            }
        });


        return bowel_movements;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const bowel_movements = await db.bowel_movements.findByPk(id, options);

        await bowel_movements.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await bowel_movements.destroy({
            transaction
        });

        return bowel_movements;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const bowel_movements = await db.bowel_movements.findOne(
            { where },
            { transaction },
        );

        if (!bowel_movements) {
            return bowel_movements;
        }

        const output = bowel_movements.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await bowel_movements.getUser({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.associated_symptoms) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bowel_movements',
                        'associated_symptoms',
                        filter.associated_symptoms,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bowel_movements',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            occurred_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    occurred_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

            
            if (filter.occurred_atRange) {
                const [start, end] = filter.occurred_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    occurred_at: {
                    ...where.occurred_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    occurred_at: {
                    ...where.occurred_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.bristol_type) {
                where = {
                    ...where,
                bristol_type: filter.bristol_type,
            };
            }
            
            if (filter.color) {
                where = {
                    ...where,
                color: filter.color,
            };
            }
            
            if (filter.blood_present) {
                where = {
                    ...where,
                blood_present: filter.blood_present,
            };
            }
            
            if (filter.mucus_present) {
                where = {
                    ...where,
                mucus_present: filter.mucus_present,
            };
            }
            


      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.bowel_movements.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'bowel_movements',
                        'notes',
                        query,
                    ),
                ],
            };
        }

        const records = await db.bowel_movements.findAll({
            attributes: [ 'id', 'notes' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['notes', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.notes,
        }));
    }

    
};

