
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
            ,
            
        receipt_date: data.receipt_date
        ||
        null
            ,
            
        posted_date: data.posted_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        remarks: data.remarks
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await goods_receipts.setCompany( data.company || null, {
            transaction,
        });
        
        await goods_receipts.setPurchase_order( data.purchase_order || null, {
            transaction,
        });
        
        await goods_receipts.setReceived_by( data.received_by || null, {
            transaction,
        });
        
        await goods_receipts.setWarehouse( data.warehouse || null, {
            transaction,
        });
        
        await goods_receipts.setOrganizations( data.organizations || 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
            ,
            
                receipt_date: item.receipt_date
            ||
            null
            ,
            
                posted_date: item.posted_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                remarks: item.remarks
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

        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.receipt_date !== undefined) updatePayload.receipt_date = data.receipt_date;
        
        
        if (data.posted_date !== undefined) updatePayload.posted_date = data.posted_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.remarks !== undefined) updatePayload.remarks = data.remarks;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await goods_receipts.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.purchase_order !== undefined) {
            await goods_receipts.setPurchase_order(
              
              data.purchase_order,
              
              { transaction }
            );
        }
        
        if (data.received_by !== undefined) {
            await goods_receipts.setReceived_by(
              
              data.received_by,
              
              { transaction }
            );
        }
        
        if (data.warehouse !== undefined) {
            await goods_receipts.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await goods_receipts.setOrganizations(
              
              data.organizations,
              
              { 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.goods_receipt_lines_goods_receipt = await goods_receipts.getGoods_receipt_lines_goods_receipt({
            transaction
        });
        
        
        output.vendor_invoices_goods_receipt = await goods_receipts.getVendor_invoices_goods_receipt({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await goods_receipts.getCompany({
            transaction
        });
        
        
        output.purchase_order = await goods_receipts.getPurchase_order({
            transaction
        });
        
        
        output.received_by = await goods_receipts.getReceived_by({
            transaction
        });
        
        
        output.warehouse = await goods_receipts.getWarehouse({
            transaction
        });
        
        
        output.attachments = await goods_receipts.getAttachments({
            transaction
        });
        
        
        output.organizations = await goods_receipts.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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              company_name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.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.warehouses,
        as: 'warehouse',
        
        where: filter.warehouse ? {
          [Op.or]: [
            { id: { [Op.in]: filter.warehouse.split('|').map(term => Utils.uuid(term)) } },
            {
              warehouse_name: {
                [Op.or]: filter.warehouse.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        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.remarks) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'goods_receipts',
                        'remarks',
                        filter.remarks,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            receipt_date: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    posted_date: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    posted_date: {
                    ...where.posted_date,
                            [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.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.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        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,
        }));
    }

    
};

