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

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

        const formula_feeding_logs = await db.formula_feeding_logs.create(
            {
                id: data.id || undefined,
        
        fed_at: data.fed_at
        ||
        null
            ,
            
        volume_ml: data.volume_ml
        ||
        null
            ,
            
        formula_brand: data.formula_brand
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return formula_feeding_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 formula_feeding_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                fed_at: item.fed_at
            ||
            null
            ,
            
                volume_ml: item.volume_ml
            ||
            null
            ,
            
                formula_brand: item.formula_brand
            ||
            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 formula_feeding_logs = await db.formula_feeding_logs.bulkCreate(formula_feeding_logsData, { transaction });

        // For each item created, replace relation files
        

        return formula_feeding_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.fed_at !== undefined) updatePayload.fed_at = data.fed_at;
        
        
        if (data.volume_ml !== undefined) updatePayload.volume_ml = data.volume_ml;
        
        
        if (data.formula_brand !== undefined) updatePayload.formula_brand = data.formula_brand;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return formula_feeding_logs;
    }

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

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

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


        return formula_feeding_logs;
    }

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

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

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

        await formula_feeding_logs.destroy({
            transaction
        });

        return formula_feeding_logs;
    }

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

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

        if (!formula_feeding_logs) {
            return formula_feeding_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.pregnancy = await formula_feeding_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.formula_brand) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'formula_feeding_logs',
                        'formula_brand',
                        filter.formula_brand,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'formula_feeding_logs',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    volume_ml: {
                    ...where.volume_ml,
                            [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.formula_feeding_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(
                        'formula_feeding_logs',
                        'formula_brand',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

