
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
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        supplier_delivery_note: data.supplier_delivery_note
        ||
        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.setBranch( data.branch || null, {
            transaction,
        });
        
        await goods_receipts.setWarehouse( data.warehouse || null, {
            transaction,
        });
        
        await goods_receipts.setReceived_by( data.received_by || null, {
            transaction,
        });
        
        await goods_receipts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        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
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                supplier_delivery_note: item.supplier_delivery_note
            ||
            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
        

        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.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.supplier_delivery_note !== undefined) updatePayload.supplier_delivery_note = data.supplier_delivery_note;
        
        
        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.branch !== undefined) {
            await goods_receipts.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.warehouse !== undefined) {
            await goods_receipts.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        
        if (data.received_by !== undefined) {
            await goods_receipts.setReceived_by(
              
              data.received_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await goods_receipts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        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.supplier_invoices_goods_receipt = await goods_receipts.getSupplier_invoices_goods_receipt({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.purchase_order = await goods_receipts.getPurchase_order({
            transaction
        });
        
        
        output.branch = await goods_receipts.getBranch({
            transaction
        });
        
        
        output.warehouse = await goods_receipts.getWarehouse({
            transaction
        });
        
        
        output.received_by = await goods_receipts.getReceived_by({
            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.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.branches,
        as: 'branch',
        
        where: filter.branch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.branch.split('|').map(term => Utils.uuid(term)) } },
            {
              branch_name: {
                [Op.or]: filter.branch.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.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.organizations,
        as: 'organizations',
        
      },



    ];

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

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

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

    
};

