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

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

        const production_outputs = await db.production_outputs.create(
            {
                id: data.id || undefined,
        
        quantity_produced: data.quantity_produced
        ||
        null
            ,
            
        lot_number: data.lot_number
        ||
        null
            ,
            
        reported_at: data.reported_at
        ||
        null
            ,
            
        qa_status: data.qa_status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await production_outputs.setProduction_order( data.production_order || null, {
            transaction,
        });
        
        await production_outputs.setItem( data.item || null, {
            transaction,
        });
        
        await production_outputs.setTo_location( data.to_location || null, {
            transaction,
        });
        
        await production_outputs.setReported_by( data.reported_by || null, {
            transaction,
        });
        

        

        

        return production_outputs;
    }
    

    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 production_outputsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                quantity_produced: item.quantity_produced
            ||
            null
            ,
            
                lot_number: item.lot_number
            ||
            null
            ,
            
                reported_at: item.reported_at
            ||
            null
            ,
            
                qa_status: item.qa_status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const production_outputs = await db.production_outputs.bulkCreate(production_outputsData, { transaction });

        // For each item created, replace relation files
        

        return production_outputs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.quantity_produced !== undefined) updatePayload.quantity_produced = data.quantity_produced;
        
        
        if (data.lot_number !== undefined) updatePayload.lot_number = data.lot_number;
        
        
        if (data.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
        
        
        if (data.qa_status !== undefined) updatePayload.qa_status = data.qa_status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.production_order !== undefined) {
            await production_outputs.setProduction_order(
              
              data.production_order,
              
              { transaction }
            );
        }
        
        if (data.item !== undefined) {
            await production_outputs.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.to_location !== undefined) {
            await production_outputs.setTo_location(
              
              data.to_location,
              
              { transaction }
            );
        }
        
        if (data.reported_by !== undefined) {
            await production_outputs.setReported_by(
              
              data.reported_by,
              
              { transaction }
            );
        }
        

        
        

        

        return production_outputs;
    }

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

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

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


        return production_outputs;
    }

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

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

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

        await production_outputs.destroy({
            transaction
        });

        return production_outputs;
    }

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

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

        if (!production_outputs) {
            return production_outputs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.production_order = await production_outputs.getProduction_order({
            transaction
        });
        
        
        output.item = await production_outputs.getItem({
            transaction
        });
        
        
        output.to_location = await production_outputs.getTo_location({
            transaction
        });
        
        
        output.reported_by = await production_outputs.getReported_by({
            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.production_orders,
        as: 'production_order',
        
        where: filter.production_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.production_order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.production_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

            
            if (filter.lot_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_outputs',
                        'lot_number',
                        filter.lot_number,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

      

      



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

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

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

    
};

