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

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

        const menstrual_day_logs = await db.menstrual_day_logs.create(
            {
                id: data.id || undefined,
        
        log_date: data.log_date
        ||
        null
            ,
            
        flow_intensity: data.flow_intensity
        ||
        null
            ,
            
        cramping: data.cramping
        ||
        null
            ,
            
        bloating: data.bloating
        ||
        null
            ,
            
        acne: data.acne
        ||
        false
        
            ,
            
        breast_tenderness: data.breast_tenderness
        ||
        false
        
            ,
            
        headache: data.headache
        ||
        false
        
            ,
            
        fatigue: data.fatigue
        ||
        false
        
            ,
            
        food_cravings: data.food_cravings
        ||
        false
        
            ,
            
        lower_back_pain: data.lower_back_pain
        ||
        false
        
            ,
            
        clotting: data.clotting
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await menstrual_day_logs.setCycle( data.cycle || null, {
            transaction,
        });
        

        

        

        return menstrual_day_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 menstrual_day_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                log_date: item.log_date
            ||
            null
            ,
            
                flow_intensity: item.flow_intensity
            ||
            null
            ,
            
                cramping: item.cramping
            ||
            null
            ,
            
                bloating: item.bloating
            ||
            null
            ,
            
                acne: item.acne
            ||
            false
        
            ,
            
                breast_tenderness: item.breast_tenderness
            ||
            false
        
            ,
            
                headache: item.headache
            ||
            false
        
            ,
            
                fatigue: item.fatigue
            ||
            false
        
            ,
            
                food_cravings: item.food_cravings
            ||
            false
        
            ,
            
                lower_back_pain: item.lower_back_pain
            ||
            false
        
            ,
            
                clotting: item.clotting
            ||
            false
        
            ,
            
                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 menstrual_day_logs = await db.menstrual_day_logs.bulkCreate(menstrual_day_logsData, { transaction });

        // For each item created, replace relation files
        

        return menstrual_day_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.log_date !== undefined) updatePayload.log_date = data.log_date;
        
        
        if (data.flow_intensity !== undefined) updatePayload.flow_intensity = data.flow_intensity;
        
        
        if (data.cramping !== undefined) updatePayload.cramping = data.cramping;
        
        
        if (data.bloating !== undefined) updatePayload.bloating = data.bloating;
        
        
        if (data.acne !== undefined) updatePayload.acne = data.acne;
        
        
        if (data.breast_tenderness !== undefined) updatePayload.breast_tenderness = data.breast_tenderness;
        
        
        if (data.headache !== undefined) updatePayload.headache = data.headache;
        
        
        if (data.fatigue !== undefined) updatePayload.fatigue = data.fatigue;
        
        
        if (data.food_cravings !== undefined) updatePayload.food_cravings = data.food_cravings;
        
        
        if (data.lower_back_pain !== undefined) updatePayload.lower_back_pain = data.lower_back_pain;
        
        
        if (data.clotting !== undefined) updatePayload.clotting = data.clotting;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.cycle !== undefined) {
            await menstrual_day_logs.setCycle(
              
              data.cycle,
              
              { transaction }
            );
        }
        

        
        

        

        return menstrual_day_logs;
    }

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

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

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


        return menstrual_day_logs;
    }

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

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

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

        await menstrual_day_logs.destroy({
            transaction
        });

        return menstrual_day_logs;
    }

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

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

        if (!menstrual_day_logs) {
            return menstrual_day_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cycle = await menstrual_day_logs.getCycle({
            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.menstrual_cycles,
        as: 'cycle',
        
        where: filter.cycle ? {
          [Op.or]: [
            { id: { [Op.in]: filter.cycle.split('|').map(term => Utils.uuid(term)) } },
            {
              notes: {
                [Op.or]: filter.cycle.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(
                        'menstrual_day_logs',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

            
            if (filter.flow_intensity) {
                where = {
                    ...where,
                flow_intensity: filter.flow_intensity,
            };
            }
            
            if (filter.acne) {
                where = {
                    ...where,
                acne: filter.acne,
            };
            }
            
            if (filter.breast_tenderness) {
                where = {
                    ...where,
                breast_tenderness: filter.breast_tenderness,
            };
            }
            
            if (filter.headache) {
                where = {
                    ...where,
                headache: filter.headache,
            };
            }
            
            if (filter.fatigue) {
                where = {
                    ...where,
                fatigue: filter.fatigue,
            };
            }
            
            if (filter.food_cravings) {
                where = {
                    ...where,
                food_cravings: filter.food_cravings,
            };
            }
            
            if (filter.lower_back_pain) {
                where = {
                    ...where,
                lower_back_pain: filter.lower_back_pain,
            };
            }
            
            if (filter.clotting) {
                where = {
                    ...where,
                clotting: filter.clotting,
            };
            }
            


      



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

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

    
};

