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

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

        const egg_collections = await db.egg_collections.create(
            {
                id: data.id || undefined,
        
        collected_at: data.collected_at
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        broken_quantity: data.broken_quantity
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await egg_collections.setPoultry_lot( data.poultry_lot || null, {
            transaction,
        });
        
        await egg_collections.setRecorded_by_user( data.recorded_by_user || null, {
            transaction,
        });
        

        

        

        return egg_collections;
    }
    

    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 egg_collectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                collected_at: item.collected_at
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                broken_quantity: item.broken_quantity
            ||
            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 egg_collections = await db.egg_collections.bulkCreate(egg_collectionsData, { transaction });

        // For each item created, replace relation files
        

        return egg_collections;
    }

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

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


        

        const updatePayload = {};
        
        if (data.collected_at !== undefined) updatePayload.collected_at = data.collected_at;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.broken_quantity !== undefined) updatePayload.broken_quantity = data.broken_quantity;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.poultry_lot !== undefined) {
            await egg_collections.setPoultry_lot(
              
              data.poultry_lot,
              
              { transaction }
            );
        }
        
        if (data.recorded_by_user !== undefined) {
            await egg_collections.setRecorded_by_user(
              
              data.recorded_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return egg_collections;
    }

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

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

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


        return egg_collections;
    }

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

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

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

        await egg_collections.destroy({
            transaction
        });

        return egg_collections;
    }

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

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

        if (!egg_collections) {
            return egg_collections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.poultry_lot = await egg_collections.getPoultry_lot({
            transaction
        });
        
        
        output.recorded_by_user = await egg_collections.getRecorded_by_user({
            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.poultry_lots,
        as: 'poultry_lot',
        
        where: filter.poultry_lot ? {
          [Op.or]: [
            { id: { [Op.in]: filter.poultry_lot.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.poultry_lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'recorded_by_user',
        
        where: filter.recorded_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.recorded_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.recorded_by_user.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(
                        'egg_collections',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

    
};

