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

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

        const shipment_updates = await db.shipment_updates.create(
            {
                id: data.id || undefined,
        
        shipment_status: data.shipment_status
        ||
        null
            ,
            
        carrier: data.carrier
        ||
        null
            ,
            
        tracking_number: data.tracking_number
        ||
        null
            ,
            
        status_at: data.status_at
        ||
        null
            ,
            
        status_details: data.status_details
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await shipment_updates.setOrder( data.order || null, {
            transaction,
        });
        
        await shipment_updates.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return shipment_updates;
    }
    

    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 shipment_updatesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                shipment_status: item.shipment_status
            ||
            null
            ,
            
                carrier: item.carrier
            ||
            null
            ,
            
                tracking_number: item.tracking_number
            ||
            null
            ,
            
                status_at: item.status_at
            ||
            null
            ,
            
                status_details: item.status_details
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return shipment_updates;
    }

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


        

        const updatePayload = {};
        
        if (data.shipment_status !== undefined) updatePayload.shipment_status = data.shipment_status;
        
        
        if (data.carrier !== undefined) updatePayload.carrier = data.carrier;
        
        
        if (data.tracking_number !== undefined) updatePayload.tracking_number = data.tracking_number;
        
        
        if (data.status_at !== undefined) updatePayload.status_at = data.status_at;
        
        
        if (data.status_details !== undefined) updatePayload.status_details = data.status_details;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.order !== undefined) {
            await shipment_updates.setOrder(
              
              data.order,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await shipment_updates.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return shipment_updates;
    }

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

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

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


        return shipment_updates;
    }

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

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

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

        await shipment_updates.destroy({
            transaction
        });

        return shipment_updates;
    }

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

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

        if (!shipment_updates) {
            return shipment_updates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.order = await shipment_updates.getOrder({
            transaction
        });
        
        
        output.organizations = await shipment_updates.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.orders,
        as: 'order',
        
        where: filter.order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.order.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.carrier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'shipment_updates',
                        'carrier',
                        filter.carrier,
                    ),
                };
            }
            
            if (filter.tracking_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'shipment_updates',
                        'tracking_number',
                        filter.tracking_number,
                    ),
                };
            }
            
            if (filter.status_details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'shipment_updates',
                        'status_details',
                        filter.status_details,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    status_at: {
                    ...where.status_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.shipment_status) {
                where = {
                    ...where,
                shipment_status: filter.shipment_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.shipment_updates.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(
                        'shipment_updates',
                        'tracking_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

