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

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

        const harvests = await db.harvests.create(
            {
                id: data.id || undefined,
        
        harvested_at: data.harvested_at
        ||
        null
            ,
            
        total_weight_kg: data.total_weight_kg
        ||
        null
            ,
            
        total_count: data.total_count
        ||
        null
            ,
            
        avg_weight_g: data.avg_weight_g
        ||
        null
            ,
            
        grade: data.grade
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return harvests;
    }
    

    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 harvestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                harvested_at: item.harvested_at
            ||
            null
            ,
            
                total_weight_kg: item.total_weight_kg
            ||
            null
            ,
            
                total_count: item.total_count
            ||
            null
            ,
            
                avg_weight_g: item.avg_weight_g
            ||
            null
            ,
            
                grade: item.grade
            ||
            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 harvests = await db.harvests.bulkCreate(harvestsData, { transaction });

        // For each item created, replace relation files
        

        return harvests;
    }

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


        

        const updatePayload = {};
        
        if (data.harvested_at !== undefined) updatePayload.harvested_at = data.harvested_at;
        
        
        if (data.total_weight_kg !== undefined) updatePayload.total_weight_kg = data.total_weight_kg;
        
        
        if (data.total_count !== undefined) updatePayload.total_count = data.total_count;
        
        
        if (data.avg_weight_g !== undefined) updatePayload.avg_weight_g = data.avg_weight_g;
        
        
        if (data.grade !== undefined) updatePayload.grade = data.grade;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return harvests;
    }

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

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

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


        return harvests;
    }

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

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

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

        await harvests.destroy({
            transaction
        });

        return harvests;
    }

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

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

        if (!harvests) {
            return harvests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.marketplace_listings_harvest = await harvests.getMarketplace_listings_harvest({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await harvests.getTenant({
            transaction
        });
        
        
        output.batch = await harvests.getBatch({
            transaction
        });
        
        
        output.recorded_by = await harvests.getRecorded_by({
            transaction
        });
        
        
        output.organizations = await harvests.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.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(
                        'harvests',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      

      

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

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

    
};

