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

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

        const feed_products = await db.feed_products.create(
            {
                id: data.id || undefined,
        
        product_name: data.product_name
        ||
        null
            ,
            
        brand: data.brand
        ||
        null
            ,
            
        feed_type: data.feed_type
        ||
        null
            ,
            
        protein_percent: data.protein_percent
        ||
        null
            ,
            
        fat_percent: data.fat_percent
        ||
        null
            ,
            
        pellet_size_mm: data.pellet_size_mm
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await feed_products.setTenant( data.tenant || null, {
            transaction,
        });
        
        await feed_products.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return feed_products;
    }
    

    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 feed_productsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                product_name: item.product_name
            ||
            null
            ,
            
                brand: item.brand
            ||
            null
            ,
            
                feed_type: item.feed_type
            ||
            null
            ,
            
                protein_percent: item.protein_percent
            ||
            null
            ,
            
                fat_percent: item.fat_percent
            ||
            null
            ,
            
                pellet_size_mm: item.pellet_size_mm
            ||
            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 feed_products = await db.feed_products.bulkCreate(feed_productsData, { transaction });

        // For each item created, replace relation files
        

        return feed_products;
    }

    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 feed_products = await db.feed_products.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.product_name !== undefined) updatePayload.product_name = data.product_name;
        
        
        if (data.brand !== undefined) updatePayload.brand = data.brand;
        
        
        if (data.feed_type !== undefined) updatePayload.feed_type = data.feed_type;
        
        
        if (data.protein_percent !== undefined) updatePayload.protein_percent = data.protein_percent;
        
        
        if (data.fat_percent !== undefined) updatePayload.fat_percent = data.fat_percent;
        
        
        if (data.pellet_size_mm !== undefined) updatePayload.pellet_size_mm = data.pellet_size_mm;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await feed_products.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await feed_products.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return feed_products;
    }

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

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

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


        return feed_products;
    }

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

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

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

        await feed_products.destroy({
            transaction
        });

        return feed_products;
    }

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

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

        if (!feed_products) {
            return feed_products;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.inventory_items_feed_product = await feed_products.getInventory_items_feed_product({
            transaction
        });
        
        
        
        output.feeding_logs_feed_product = await feed_products.getFeeding_logs_feed_product({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await feed_products.getTenant({
            transaction
        });
        
        
        output.organizations = await feed_products.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.product_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'feed_products',
                        'product_name',
                        filter.product_name,
                    ),
                };
            }
            
            if (filter.brand) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'feed_products',
                        'brand',
                        filter.brand,
                    ),
                };
            }
            
            if (filter.feed_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'feed_products',
                        'feed_type',
                        filter.feed_type,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'feed_products',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            


      

      
      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.feed_products.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(
                        'feed_products',
                        'product_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

