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

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

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

        
        await interbranch_transfers.setFrom_branch( data.from_branch || null, {
            transaction,
        });
        
        await interbranch_transfers.setTo_branch( data.to_branch || null, {
            transaction,
        });
        
        await interbranch_transfers.setFrom_warehouse( data.from_warehouse || null, {
            transaction,
        });
        
        await interbranch_transfers.setTo_warehouse( data.to_warehouse || null, {
            transaction,
        });
        
        await interbranch_transfers.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await interbranch_transfers.setReceived_by( data.received_by || null, {
            transaction,
        });
        
        await interbranch_transfers.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return interbranch_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 interbranch_transfersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                transfer_number: item.transfer_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                dispatched_at: item.dispatched_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 interbranch_transfers = await db.interbranch_transfers.bulkCreate(interbranch_transfersData, { transaction });

        // For each item created, replace relation files
        

        return interbranch_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 interbranch_transfers = await db.interbranch_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.dispatched_at !== undefined) updatePayload.dispatched_at = data.dispatched_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 interbranch_transfers.update(updatePayload, {transaction});

        
        
        if (data.from_branch !== undefined) {
            await interbranch_transfers.setFrom_branch(
              
              data.from_branch,
              
              { transaction }
            );
        }
        
        if (data.to_branch !== undefined) {
            await interbranch_transfers.setTo_branch(
              
              data.to_branch,
              
              { transaction }
            );
        }
        
        if (data.from_warehouse !== undefined) {
            await interbranch_transfers.setFrom_warehouse(
              
              data.from_warehouse,
              
              { transaction }
            );
        }
        
        if (data.to_warehouse !== undefined) {
            await interbranch_transfers.setTo_warehouse(
              
              data.to_warehouse,
              
              { transaction }
            );
        }
        
        if (data.requested_by !== undefined) {
            await interbranch_transfers.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.received_by !== undefined) {
            await interbranch_transfers.setReceived_by(
              
              data.received_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await interbranch_transfers.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return interbranch_transfers;
    }

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

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

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


        return interbranch_transfers;
    }

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

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

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

        await interbranch_transfers.destroy({
            transaction
        });

        return interbranch_transfers;
    }

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

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

        if (!interbranch_transfers) {
            return interbranch_transfers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.transfer_lines_transfer = await interbranch_transfers.getTransfer_lines_transfer({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.from_branch = await interbranch_transfers.getFrom_branch({
            transaction
        });
        
        
        output.to_branch = await interbranch_transfers.getTo_branch({
            transaction
        });
        
        
        output.from_warehouse = await interbranch_transfers.getFrom_warehouse({
            transaction
        });
        
        
        output.to_warehouse = await interbranch_transfers.getTo_warehouse({
            transaction
        });
        
        
        output.requested_by = await interbranch_transfers.getRequested_by({
            transaction
        });
        
        
        output.received_by = await interbranch_transfers.getReceived_by({
            transaction
        });
        
        
        output.organizations = await interbranch_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.branches,
        as: 'from_branch',
        
        where: filter.from_branch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.from_branch.split('|').map(term => Utils.uuid(term)) } },
            {
              branch_name: {
                [Op.or]: filter.from_branch.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.warehouses,
        as: 'to_warehouse',
        
        where: filter.to_warehouse ? {
          [Op.or]: [
            { id: { [Op.in]: filter.to_warehouse.split('|').map(term => Utils.uuid(term)) } },
            {
              warehouse_name: {
                [Op.or]: filter.to_warehouse.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.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.transfer_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'interbranch_transfers',
                        'transfer_number',
                        filter.transfer_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'interbranch_transfers',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    dispatched_at: {
                    ...where.dispatched_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.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.interbranch_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(
                        'interbranch_transfers',
                        'transfer_number',
                        query,
                    ),
                ],
            };
        }

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

    
};

