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

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

        const breastfeeding_logs = await db.breastfeeding_logs.create(
            {
                id: data.id || undefined,
        
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        side: data.side
        ||
        null
            ,
            
        duration_minutes: data.duration_minutes
        ||
        null
            ,
            
        latch_notes: data.latch_notes
        ||
        null
            ,
            
        production_notes: data.production_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return breastfeeding_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 breastfeeding_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                side: item.side
            ||
            null
            ,
            
                duration_minutes: item.duration_minutes
            ||
            null
            ,
            
                latch_notes: item.latch_notes
            ||
            null
            ,
            
                production_notes: item.production_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return breastfeeding_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.side !== undefined) updatePayload.side = data.side;
        
        
        if (data.duration_minutes !== undefined) updatePayload.duration_minutes = data.duration_minutes;
        
        
        if (data.latch_notes !== undefined) updatePayload.latch_notes = data.latch_notes;
        
        
        if (data.production_notes !== undefined) updatePayload.production_notes = data.production_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return breastfeeding_logs;
    }

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

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

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


        return breastfeeding_logs;
    }

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

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

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

        await breastfeeding_logs.destroy({
            transaction
        });

        return breastfeeding_logs;
    }

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

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

        if (!breastfeeding_logs) {
            return breastfeeding_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.pregnancy = await breastfeeding_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.latch_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'breastfeeding_logs',
                        'latch_notes',
                        filter.latch_notes,
                    ),
                };
            }
            
            if (filter.production_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'breastfeeding_logs',
                        'production_notes',
                        filter.production_notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

            
            if (filter.side) {
                where = {
                    ...where,
                side: filter.side,
            };
            }
            


      



            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.breastfeeding_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(
                        'breastfeeding_logs',
                        'latch_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

