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

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

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

        
        await stock_transfers.setFrom_store( data.from_store || null, {
            transaction,
        });
        
        await stock_transfers.setTo_store( data.to_store || null, {
            transaction,
        });
        
        await stock_transfers.setRequested_by_user( data.requested_by_user || null, {
            transaction,
        });
        
        await stock_transfers.setApproved_by_user( data.approved_by_user || null, {
            transaction,
        });
        
        await stock_transfers.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.transfer_number !== undefined) updatePayload.transfer_number = data.transfer_number;
        
        
        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.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.from_store !== undefined) {
            await stock_transfers.setFrom_store(
              
              data.from_store,
              
              { transaction }
            );
        }
        
        if (data.to_store !== undefined) {
            await stock_transfers.setTo_store(
              
              data.to_store,
              
              { transaction }
            );
        }
        
        if (data.requested_by_user !== undefined) {
            await stock_transfers.setRequested_by_user(
              
              data.requested_by_user,
              
              { transaction }
            );
        }
        
        if (data.approved_by_user !== undefined) {
            await stock_transfers.setApproved_by_user(
              
              data.approved_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await stock_transfers.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return stock_transfers;
    }

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

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

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


        return stock_transfers;
    }

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

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

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

        await stock_transfers.destroy({
            transaction
        });

        return stock_transfers;
    }

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

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

        if (!stock_transfers) {
            return stock_transfers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.stock_transfer_items_stock_transfer = await stock_transfers.getStock_transfer_items_stock_transfer({
            transaction
        });
        
        
        
        output.from_store = await stock_transfers.getFrom_store({
            transaction
        });
        
        
        output.to_store = await stock_transfers.getTo_store({
            transaction
        });
        
        
        output.requested_by_user = await stock_transfers.getRequested_by_user({
            transaction
        });
        
        
        output.approved_by_user = await stock_transfers.getApproved_by_user({
            transaction
        });
        
        
        output.organizations = await stock_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.stores,
        as: 'from_store',
        
        where: filter.from_store ? {
          [Op.or]: [
            { id: { [Op.in]: filter.from_store.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.from_store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

    
};

