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

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

        const goods_receipt_notes = await db.goods_receipt_notes.create(
            {
                id: data.id || undefined,
        
        grn_number: data.grn_number
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        quality_check: data.quality_check
        ||
        null
            ,
            
        observations: data.observations
        ||
        null
            ,
            
        receiver_signature: data.receiver_signature
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await goods_receipt_notes.setTenant( data.tenant || null, {
            transaction,
        });
        
        await goods_receipt_notes.setPurchase_order( data.purchase_order || null, {
            transaction,
        });
        
        await goods_receipt_notes.setReceived_by( data.received_by || null, {
            transaction,
        });
        
        await goods_receipt_notes.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return goods_receipt_notes;
    }
    

    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_receipt_notesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                grn_number: item.grn_number
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                quality_check: item.quality_check
            ||
            null
            ,
            
                observations: item.observations
            ||
            null
            ,
            
                receiver_signature: item.receiver_signature
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return goods_receipt_notes;
    }

    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_receipt_notes = await db.goods_receipt_notes.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.grn_number !== undefined) updatePayload.grn_number = data.grn_number;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.quality_check !== undefined) updatePayload.quality_check = data.quality_check;
        
        
        if (data.observations !== undefined) updatePayload.observations = data.observations;
        
        
        if (data.receiver_signature !== undefined) updatePayload.receiver_signature = data.receiver_signature;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await goods_receipt_notes.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.purchase_order !== undefined) {
            await goods_receipt_notes.setPurchase_order(
              
              data.purchase_order,
              
              { transaction }
            );
        }
        
        if (data.received_by !== undefined) {
            await goods_receipt_notes.setReceived_by(
              
              data.received_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await goods_receipt_notes.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return goods_receipt_notes;
    }

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

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

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


        return goods_receipt_notes;
    }

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

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

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

        await goods_receipt_notes.destroy({
            transaction
        });

        return goods_receipt_notes;
    }

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

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

        if (!goods_receipt_notes) {
            return goods_receipt_notes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.grn_lines_goods_receipt_note = await goods_receipt_notes.getGrn_lines_goods_receipt_note({
            transaction
        });
        
        
        
        output.discrepancy_cases_goods_receipt_note = await goods_receipt_notes.getDiscrepancy_cases_goods_receipt_note({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.tenant = await goods_receipt_notes.getTenant({
            transaction
        });
        
        
        output.purchase_order = await goods_receipt_notes.getPurchase_order({
            transaction
        });
        
        
        output.received_by = await goods_receipt_notes.getReceived_by({
            transaction
        });
        
        
        output.photos = await goods_receipt_notes.getPhotos({
            transaction
        });
        
        
        output.organizations = await goods_receipt_notes.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.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.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.grn_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'goods_receipt_notes',
                        'grn_number',
                        filter.grn_number,
                    ),
                };
            }
            
            if (filter.observations) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'goods_receipt_notes',
                        'observations',
                        filter.observations,
                    ),
                };
            }
            
            if (filter.receiver_signature) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'goods_receipt_notes',
                        'receiver_signature',
                        filter.receiver_signature,
                    ),
                };
            }
            

            
            

            
            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.quality_check) {
                where = {
                    ...where,
                quality_check: filter.quality_check,
            };
            }
            
            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_receipt_notes.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_receipt_notes',
                        'grn_number',
                        query,
                    ),
                ],
            };
        }

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

    
};

