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

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

        const goods_receipts = await db.goods_receipts.create(
            {
                id: data.id || undefined,
        
        grn_number: data.grn_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        carrier: data.carrier
        ||
        null
            ,
            
        tracking_number: data.tracking_number
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await goods_receipts.setPurchase_order( data.purchase_order || null, {
            transaction,
        });
        
        await goods_receipts.setReceived_to_location( data.received_to_location || null, {
            transaction,
        });
        
        await goods_receipts.setReceived_by( data.received_by || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.goods_receipts.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: goods_receipts.id,
            },
            data.attachments,
            options,
        );
        

        return goods_receipts;
    }
    

    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 goods_receiptsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                grn_number: item.grn_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                carrier: item.carrier
            ||
            null
            ,
            
                tracking_number: item.tracking_number
            ||
            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 goods_receipts = await db.goods_receipts.bulkCreate(goods_receiptsData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < goods_receipts.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.goods_receipts.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: goods_receipts[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return goods_receipts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.grn_number !== undefined) updatePayload.grn_number = data.grn_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.carrier !== undefined) updatePayload.carrier = data.carrier;
        
        
        if (data.tracking_number !== undefined) updatePayload.tracking_number = data.tracking_number;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.purchase_order !== undefined) {
            await goods_receipts.setPurchase_order(
              
              data.purchase_order,
              
              { transaction }
            );
        }
        
        if (data.received_to_location !== undefined) {
            await goods_receipts.setReceived_to_location(
              
              data.received_to_location,
              
              { transaction }
            );
        }
        
        if (data.received_by !== undefined) {
            await goods_receipts.setReceived_by(
              
              data.received_by,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.goods_receipts.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: goods_receipts.id,
            },
            data.attachments,
            options,
        );
        

        return goods_receipts;
    }

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

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

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


        return goods_receipts;
    }

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

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

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

        await goods_receipts.destroy({
            transaction
        });

        return goods_receipts;
    }

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

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

        if (!goods_receipts) {
            return goods_receipts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.purchase_order = await goods_receipts.getPurchase_order({
            transaction
        });
        
        
        output.received_to_location = await goods_receipts.getReceived_to_location({
            transaction
        });
        
        
        output.attachments = await goods_receipts.getAttachments({
            transaction
        });
        
        
        output.received_by = await goods_receipts.getReceived_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.purchase_orders,
        as: 'purchase_order',
        
        where: filter.purchase_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.purchase_order.split('|').map(term => Utils.uuid(term)) } },
            {
              po_number: {
                [Op.or]: filter.purchase_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

            
            if (filter.grn_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'goods_receipts',
                        'grn_number',
                        filter.grn_number,
                    ),
                };
            }
            
            if (filter.carrier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'goods_receipts',
                        'carrier',
                        filter.carrier,
                    ),
                };
            }
            
            if (filter.tracking_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'goods_receipts',
                        'tracking_number',
                        filter.tracking_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'goods_receipts',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.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.goods_receipts.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(
                        'goods_receipts',
                        'grn_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

