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

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

        const deliveries = await db.deliveries.create(
            {
                id: data.id || undefined,
        
        delivery_status: data.delivery_status
        ||
        null
            ,
            
        delivery_mode: data.delivery_mode
        ||
        null
            ,
            
        pickup_latitude: data.pickup_latitude
        ||
        null
            ,
            
        pickup_longitude: data.pickup_longitude
        ||
        null
            ,
            
        dropoff_latitude: data.dropoff_latitude
        ||
        null
            ,
            
        dropoff_longitude: data.dropoff_longitude
        ||
        null
            ,
            
        distance_km: data.distance_km
        ||
        null
            ,
            
        courier_earnings: data.courier_earnings
        ||
        null
            ,
            
        platform_commission: data.platform_commission
        ||
        null
            ,
            
        assigned_at: data.assigned_at
        ||
        null
            ,
            
        picked_up_at: data.picked_up_at
        ||
        null
            ,
            
        delivered_at: data.delivered_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return deliveries;
    }
    

    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 deliveriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                delivery_status: item.delivery_status
            ||
            null
            ,
            
                delivery_mode: item.delivery_mode
            ||
            null
            ,
            
                pickup_latitude: item.pickup_latitude
            ||
            null
            ,
            
                pickup_longitude: item.pickup_longitude
            ||
            null
            ,
            
                dropoff_latitude: item.dropoff_latitude
            ||
            null
            ,
            
                dropoff_longitude: item.dropoff_longitude
            ||
            null
            ,
            
                distance_km: item.distance_km
            ||
            null
            ,
            
                courier_earnings: item.courier_earnings
            ||
            null
            ,
            
                platform_commission: item.platform_commission
            ||
            null
            ,
            
                assigned_at: item.assigned_at
            ||
            null
            ,
            
                picked_up_at: item.picked_up_at
            ||
            null
            ,
            
                delivered_at: item.delivered_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return deliveries;
    }

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


        

        const updatePayload = {};
        
        if (data.delivery_status !== undefined) updatePayload.delivery_status = data.delivery_status;
        
        
        if (data.delivery_mode !== undefined) updatePayload.delivery_mode = data.delivery_mode;
        
        
        if (data.pickup_latitude !== undefined) updatePayload.pickup_latitude = data.pickup_latitude;
        
        
        if (data.pickup_longitude !== undefined) updatePayload.pickup_longitude = data.pickup_longitude;
        
        
        if (data.dropoff_latitude !== undefined) updatePayload.dropoff_latitude = data.dropoff_latitude;
        
        
        if (data.dropoff_longitude !== undefined) updatePayload.dropoff_longitude = data.dropoff_longitude;
        
        
        if (data.distance_km !== undefined) updatePayload.distance_km = data.distance_km;
        
        
        if (data.courier_earnings !== undefined) updatePayload.courier_earnings = data.courier_earnings;
        
        
        if (data.platform_commission !== undefined) updatePayload.platform_commission = data.platform_commission;
        
        
        if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
        
        
        if (data.picked_up_at !== undefined) updatePayload.picked_up_at = data.picked_up_at;
        
        
        if (data.delivered_at !== undefined) updatePayload.delivered_at = data.delivered_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return deliveries;
    }

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

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

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


        return deliveries;
    }

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

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

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

        await deliveries.destroy({
            transaction
        });

        return deliveries;
    }

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

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

        if (!deliveries) {
            return deliveries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.order = await deliveries.getOrder({
            transaction
        });
        
        
        output.courier = await deliveries.getCourier({
            transaction
        });
        
        
        output.organizations = await deliveries.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.users,
        as: 'courier',
        
        where: filter.courier ? {
          [Op.or]: [
            { id: { [Op.in]: filter.courier.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.courier.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.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            assigned_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    delivered_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.delivery_status) {
                where = {
                    ...where,
                delivery_status: filter.delivery_status,
            };
            }
            
            if (filter.delivery_mode) {
                where = {
                    ...where,
                delivery_mode: filter.delivery_mode,
            };
            }
            


      

      

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

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

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

    
};

