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

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

        const receipt_lines = await db.receipt_lines.create(
            {
                id: data.id || undefined,
        
        quantity_received: data.quantity_received
        ||
        null
            ,
            
        lot_number: data.lot_number
        ||
        null
            ,
            
        inspection_required: data.inspection_required
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await receipt_lines.setReceipt( data.receipt || null, {
            transaction,
        });
        
        await receipt_lines.setPurchase_order_line( data.purchase_order_line || null, {
            transaction,
        });
        
        await receipt_lines.setItem( data.item || null, {
            transaction,
        });
        
        await receipt_lines.setTo_location( data.to_location || null, {
            transaction,
        });
        

        

        

        return receipt_lines;
    }
    

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

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

        // For each item created, replace relation files
        

        return receipt_lines;
    }

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

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


        

        const updatePayload = {};
        
        if (data.quantity_received !== undefined) updatePayload.quantity_received = data.quantity_received;
        
        
        if (data.lot_number !== undefined) updatePayload.lot_number = data.lot_number;
        
        
        if (data.inspection_required !== undefined) updatePayload.inspection_required = data.inspection_required;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.receipt !== undefined) {
            await receipt_lines.setReceipt(
              
              data.receipt,
              
              { transaction }
            );
        }
        
        if (data.purchase_order_line !== undefined) {
            await receipt_lines.setPurchase_order_line(
              
              data.purchase_order_line,
              
              { transaction }
            );
        }
        
        if (data.item !== undefined) {
            await receipt_lines.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.to_location !== undefined) {
            await receipt_lines.setTo_location(
              
              data.to_location,
              
              { transaction }
            );
        }
        

        
        

        

        return receipt_lines;
    }

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

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

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


        return receipt_lines;
    }

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

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

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

        await receipt_lines.destroy({
            transaction
        });

        return receipt_lines;
    }

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

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

        if (!receipt_lines) {
            return receipt_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.receipt = await receipt_lines.getReceipt({
            transaction
        });
        
        
        output.purchase_order_line = await receipt_lines.getPurchase_order_line({
            transaction
        });
        
        
        output.item = await receipt_lines.getItem({
            transaction
        });
        
        
        output.to_location = await receipt_lines.getTo_location({
            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.receipts,
        as: 'receipt',
        
        where: filter.receipt ? {
          [Op.or]: [
            { id: { [Op.in]: filter.receipt.split('|').map(term => Utils.uuid(term)) } },
            {
              receipt_number: {
                [Op.or]: filter.receipt.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.purchase_order_lines,
        as: 'purchase_order_line',
        
        where: filter.purchase_order_line ? {
          [Op.or]: [
            { id: { [Op.in]: filter.purchase_order_line.split('|').map(term => Utils.uuid(term)) } },
            {
              description: {
                [Op.or]: filter.purchase_order_line.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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


      

      

      

      



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

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

    
};

