
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 Pregnancy_symptom_logsDBApi {
    

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

        const pregnancy_symptom_logs = await db.pregnancy_symptom_logs.create(
            {
                id: data.id || undefined,
        
        logged_at: data.logged_at
        ||
        null
            ,
            
        nausea: data.nausea
        ||
        null
            ,
            
        vomiting: data.vomiting
        ||
        null
            ,
            
        fatigue: data.fatigue
        ||
        null
            ,
            
        heartburn: data.heartburn
        ||
        null
            ,
            
        swelling: data.swelling
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await pregnancy_symptom_logs.setPregnancy( data.pregnancy || null, {
            transaction,
        });
        

        

        

        return pregnancy_symptom_logs;
    }
    

    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 pregnancy_symptom_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                logged_at: item.logged_at
            ||
            null
            ,
            
                nausea: item.nausea
            ||
            null
            ,
            
                vomiting: item.vomiting
            ||
            null
            ,
            
                fatigue: item.fatigue
            ||
            null
            ,
            
                heartburn: item.heartburn
            ||
            null
            ,
            
                swelling: item.swelling
            ||
            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 pregnancy_symptom_logs = await db.pregnancy_symptom_logs.bulkCreate(pregnancy_symptom_logsData, { transaction });

        // For each item created, replace relation files
        

        return pregnancy_symptom_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.logged_at !== undefined) updatePayload.logged_at = data.logged_at;
        
        
        if (data.nausea !== undefined) updatePayload.nausea = data.nausea;
        
        
        if (data.vomiting !== undefined) updatePayload.vomiting = data.vomiting;
        
        
        if (data.fatigue !== undefined) updatePayload.fatigue = data.fatigue;
        
        
        if (data.heartburn !== undefined) updatePayload.heartburn = data.heartburn;
        
        
        if (data.swelling !== undefined) updatePayload.swelling = data.swelling;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.pregnancy !== undefined) {
            await pregnancy_symptom_logs.setPregnancy(
              
              data.pregnancy,
              
              { transaction }
            );
        }
        

        
        

        

        return pregnancy_symptom_logs;
    }

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

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

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


        return pregnancy_symptom_logs;
    }

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

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

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

        await pregnancy_symptom_logs.destroy({
            transaction
        });

        return pregnancy_symptom_logs;
    }

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

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

        if (!pregnancy_symptom_logs) {
            return pregnancy_symptom_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.pregnancy = await pregnancy_symptom_logs.getPregnancy({
            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.pregnancies,
        as: 'pregnancy',
        
        where: filter.pregnancy ? {
          [Op.or]: [
            { id: { [Op.in]: filter.pregnancy.split('|').map(term => Utils.uuid(term)) } },
            {
              notes: {
                [Op.or]: filter.pregnancy.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    logged_at: {
                    ...where.logged_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.nauseaRange) {
                const [start, end] = filter.nauseaRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    nausea: {
                    ...where.nausea,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.vomitingRange) {
                const [start, end] = filter.vomitingRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    vomiting: {
                    ...where.vomiting,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.fatigueRange) {
                const [start, end] = filter.fatigueRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    fatigue: {
                    ...where.fatigue,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.heartburnRange) {
                const [start, end] = filter.heartburnRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    heartburn: {
                    ...where.heartburn,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.swellingRange) {
                const [start, end] = filter.swellingRange;

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

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

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

            


      



            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.pregnancy_symptom_logs.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(
                        'pregnancy_symptom_logs',
                        'notes',
                        query,
                    ),
                ],
            };
        }

        const records = await db.pregnancy_symptom_logs.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,
        }));
    }

    
};

