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

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

        const batches = await db.batches.create(
            {
                id: data.id || undefined,
        
        batch_code: data.batch_code
        ||
        null
            ,
            
        stocked_at: data.stocked_at
        ||
        null
            ,
            
        initial_count: data.initial_count
        ||
        null
            ,
            
        initial_avg_weight_g: data.initial_avg_weight_g
        ||
        null
            ,
            
        batch_status: data.batch_status
        ||
        null
            ,
            
        expected_harvest_at: data.expected_harvest_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await batches.setTenant( data.tenant || null, {
            transaction,
        });
        
        await batches.setPond( data.pond || null, {
            transaction,
        });
        
        await batches.setSpecies( data.species || null, {
            transaction,
        });
        
        await batches.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return batches;
    }
    

    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 batchesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                batch_code: item.batch_code
            ||
            null
            ,
            
                stocked_at: item.stocked_at
            ||
            null
            ,
            
                initial_count: item.initial_count
            ||
            null
            ,
            
                initial_avg_weight_g: item.initial_avg_weight_g
            ||
            null
            ,
            
                batch_status: item.batch_status
            ||
            null
            ,
            
                expected_harvest_at: item.expected_harvest_at
            ||
            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 batches = await db.batches.bulkCreate(batchesData, { transaction });

        // For each item created, replace relation files
        

        return batches;
    }

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


        

        const updatePayload = {};
        
        if (data.batch_code !== undefined) updatePayload.batch_code = data.batch_code;
        
        
        if (data.stocked_at !== undefined) updatePayload.stocked_at = data.stocked_at;
        
        
        if (data.initial_count !== undefined) updatePayload.initial_count = data.initial_count;
        
        
        if (data.initial_avg_weight_g !== undefined) updatePayload.initial_avg_weight_g = data.initial_avg_weight_g;
        
        
        if (data.batch_status !== undefined) updatePayload.batch_status = data.batch_status;
        
        
        if (data.expected_harvest_at !== undefined) updatePayload.expected_harvest_at = data.expected_harvest_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await batches.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.pond !== undefined) {
            await batches.setPond(
              
              data.pond,
              
              { transaction }
            );
        }
        
        if (data.species !== undefined) {
            await batches.setSpecies(
              
              data.species,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await batches.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return batches;
    }

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

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

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


        return batches;
    }

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

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

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

        await batches.destroy({
            transaction
        });

        return batches;
    }

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

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

        if (!batches) {
            return batches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.inventory_movements_batch = await batches.getInventory_movements_batch({
            transaction
        });
        
        
        output.feeding_logs_batch = await batches.getFeeding_logs_batch({
            transaction
        });
        
        
        
        output.health_events_batch = await batches.getHealth_events_batch({
            transaction
        });
        
        
        output.harvests_batch = await batches.getHarvests_batch({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await batches.getTenant({
            transaction
        });
        
        
        output.pond = await batches.getPond({
            transaction
        });
        
        
        output.species = await batches.getSpecies({
            transaction
        });
        
        
        output.organizations = await batches.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.ponds,
        as: 'pond',
        
        where: filter.pond ? {
          [Op.or]: [
            { id: { [Op.in]: filter.pond.split('|').map(term => Utils.uuid(term)) } },
            {
              pond_name: {
                [Op.or]: filter.pond.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.species,
        as: 'species',
        
        where: filter.species ? {
          [Op.or]: [
            { id: { [Op.in]: filter.species.split('|').map(term => Utils.uuid(term)) } },
            {
              species_name: {
                [Op.or]: filter.species.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.batch_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'batches',
                        'batch_code',
                        filter.batch_code,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'batches',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      

      

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

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

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

    
};

