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

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

        const feeding_logs = await db.feeding_logs.create(
            {
                id: data.id || undefined,
        
        fed_at: data.fed_at
        ||
        null
            ,
            
        quantity_kg: data.quantity_kg
        ||
        null
            ,
            
        feeding_method: data.feeding_method
        ||
        null
            ,
            
        appetite: data.appetite
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await feeding_logs.setTenant( data.tenant || null, {
            transaction,
        });
        
        await feeding_logs.setBatch( data.batch || null, {
            transaction,
        });
        
        await feeding_logs.setFeed_product( data.feed_product || null, {
            transaction,
        });
        
        await feeding_logs.setRecorded_by( data.recorded_by || null, {
            transaction,
        });
        
        await feeding_logs.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return 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 feeding_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                fed_at: item.fed_at
            ||
            null
            ,
            
                quantity_kg: item.quantity_kg
            ||
            null
            ,
            
                feeding_method: item.feeding_method
            ||
            null
            ,
            
                appetite: item.appetite
            ||
            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 feeding_logs = await db.feeding_logs.bulkCreate(feeding_logsData, { transaction });

        // For each item created, replace relation files
        

        return feeding_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.fed_at !== undefined) updatePayload.fed_at = data.fed_at;
        
        
        if (data.quantity_kg !== undefined) updatePayload.quantity_kg = data.quantity_kg;
        
        
        if (data.feeding_method !== undefined) updatePayload.feeding_method = data.feeding_method;
        
        
        if (data.appetite !== undefined) updatePayload.appetite = data.appetite;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await feeding_logs.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.batch !== undefined) {
            await feeding_logs.setBatch(
              
              data.batch,
              
              { transaction }
            );
        }
        
        if (data.feed_product !== undefined) {
            await feeding_logs.setFeed_product(
              
              data.feed_product,
              
              { transaction }
            );
        }
        
        if (data.recorded_by !== undefined) {
            await feeding_logs.setRecorded_by(
              
              data.recorded_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await feeding_logs.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return feeding_logs;
    }

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

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

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


        return feeding_logs;
    }

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

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

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

        await feeding_logs.destroy({
            transaction
        });

        return feeding_logs;
    }

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

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

        if (!feeding_logs) {
            return feeding_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await feeding_logs.getTenant({
            transaction
        });
        
        
        output.batch = await feeding_logs.getBatch({
            transaction
        });
        
        
        output.feed_product = await feeding_logs.getFeed_product({
            transaction
        });
        
        
        output.recorded_by = await feeding_logs.getRecorded_by({
            transaction
        });
        
        
        output.organizations = await feeding_logs.getOrganizations({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        '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.quantity_kgRange) {
                const [start, end] = filter.quantity_kgRange;

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

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

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

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


      

      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

    
};

