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

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

        const inventory_transfers = await db.inventory_transfers.create(
            {
                id: data.id || undefined,
        
        transfer_number: data.transfer_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        shipped_at: data.shipped_at
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_transfers.setTenant( data.tenant || null, {
            transaction,
        });
        
        await inventory_transfers.setFrom_location( data.from_location || null, {
            transaction,
        });
        
        await inventory_transfers.setTo_location( data.to_location || null, {
            transaction,
        });
        
        await inventory_transfers.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await inventory_transfers.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await inventory_transfers.setLines(data.lines || [], {
            transaction,
        });
        

        

        return inventory_transfers;
    }
    

    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 inventory_transfersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                transfer_number: item.transfer_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                shipped_at: item.shipped_at
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            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 inventory_transfers = await db.inventory_transfers.bulkCreate(inventory_transfersData, { transaction });

        // For each item created, replace relation files
        

        return inventory_transfers;
    }

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


        

        const updatePayload = {};
        
        if (data.transfer_number !== undefined) updatePayload.transfer_number = data.transfer_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.shipped_at !== undefined) updatePayload.shipped_at = data.shipped_at;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await inventory_transfers.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.from_location !== undefined) {
            await inventory_transfers.setFrom_location(
              
              data.from_location,
              
              { transaction }
            );
        }
        
        if (data.to_location !== undefined) {
            await inventory_transfers.setTo_location(
              
              data.to_location,
              
              { transaction }
            );
        }
        
        if (data.requested_by !== undefined) {
            await inventory_transfers.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await inventory_transfers.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.lines !== undefined) {
            await inventory_transfers.setLines(data.lines, { transaction });
        }
        

        

        return inventory_transfers;
    }

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

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

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


        return inventory_transfers;
    }

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

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

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

        await inventory_transfers.destroy({
            transaction
        });

        return inventory_transfers;
    }

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

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

        if (!inventory_transfers) {
            return inventory_transfers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.inventory_transfer_lines_transfer = await inventory_transfers.getInventory_transfer_lines_transfer({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await inventory_transfers.getTenant({
            transaction
        });
        
        
        output.from_location = await inventory_transfers.getFrom_location({
            transaction
        });
        
        
        output.to_location = await inventory_transfers.getTo_location({
            transaction
        });
        
        
        output.requested_by = await inventory_transfers.getRequested_by({
            transaction
        });
        
        
        output.lines = await inventory_transfers.getLines({
            transaction
        });
        
        
        output.organizations = await inventory_transfers.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.locations,
        as: 'from_location',
        
        where: filter.from_location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.from_location.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.from_location.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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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


      {
        model: db.inventory_transfer_lines,
        as: 'lines',
        required: false,
      },


    ];

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

            
            if (filter.transfer_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_transfers',
                        'transfer_number',
                        filter.transfer_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inventory_transfers',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    shipped_at: {
                    ...where.shipped_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      


      if (filter.lines) {
        const searchTerms = filter.lines.split('|');

        include = [
          {
            model: db.inventory_transfer_lines,
            as: 'lines_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  memo: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

