
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_number: data.delivery_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        planned_ship_at: data.planned_ship_at
        ||
        null
            ,
            
        planned_delivery_at: data.planned_delivery_at
        ||
        null
            ,
            
        delivered_at: data.delivered_at
        ||
        null
            ,
            
        ship_to_address: data.ship_to_address
        ||
        null
            ,
            
        carrier: data.carrier
        ||
        null
            ,
            
        tracking_number: data.tracking_number
        ||
        null
            ,
            
        shipping_cost: data.shipping_cost
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await deliveries.setProject( data.project || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.deliveries.getTableName(),
                belongsToColumn: 'proof_of_delivery',
                belongsToId: deliveries.id,
            },
            data.proof_of_delivery,
            options,
        );
        

        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_number: item.delivery_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                planned_ship_at: item.planned_ship_at
            ||
            null
            ,
            
                planned_delivery_at: item.planned_delivery_at
            ||
            null
            ,
            
                delivered_at: item.delivered_at
            ||
            null
            ,
            
                ship_to_address: item.ship_to_address
            ||
            null
            ,
            
                carrier: item.carrier
            ||
            null
            ,
            
                tracking_number: item.tracking_number
            ||
            null
            ,
            
                shipping_cost: item.shipping_cost
            ||
            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 deliveries = await db.deliveries.bulkCreate(deliveriesData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < deliveries.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.deliveries.getTableName(),
                    belongsToColumn: 'proof_of_delivery',
                    belongsToId: deliveries[i].id,
                },
                data[i].proof_of_delivery,
                options,
            );
        }
        

        return deliveries;
    }

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

        const deliveries = await db.deliveries.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.delivery_number !== undefined) updatePayload.delivery_number = data.delivery_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.planned_ship_at !== undefined) updatePayload.planned_ship_at = data.planned_ship_at;
        
        
        if (data.planned_delivery_at !== undefined) updatePayload.planned_delivery_at = data.planned_delivery_at;
        
        
        if (data.delivered_at !== undefined) updatePayload.delivered_at = data.delivered_at;
        
        
        if (data.ship_to_address !== undefined) updatePayload.ship_to_address = data.ship_to_address;
        
        
        if (data.carrier !== undefined) updatePayload.carrier = data.carrier;
        
        
        if (data.tracking_number !== undefined) updatePayload.tracking_number = data.tracking_number;
        
        
        if (data.shipping_cost !== undefined) updatePayload.shipping_cost = data.shipping_cost;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await deliveries.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.deliveries.getTableName(),
                belongsToColumn: 'proof_of_delivery',
                belongsToId: deliveries.id,
            },
            data.proof_of_delivery,
            options,
        );
        

        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.delivery_items_delivery = await deliveries.getDelivery_items_delivery({
            transaction
        });
        
        
        
        
        
        
        
        output.project = await deliveries.getProject({
            transaction
        });
        
        
        output.proof_of_delivery = await deliveries.getProof_of_delivery({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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



      {
        model: db.file,
        as: 'proof_of_delivery',
      },

    ];

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

            
            if (filter.delivery_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deliveries',
                        'delivery_number',
                        filter.delivery_number,
                    ),
                };
            }
            
            if (filter.ship_to_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deliveries',
                        'ship_to_address',
                        filter.ship_to_address,
                    ),
                };
            }
            
            if (filter.carrier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deliveries',
                        'carrier',
                        filter.carrier,
                    ),
                };
            }
            
            if (filter.tracking_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deliveries',
                        'tracking_number',
                        filter.tracking_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deliveries',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            planned_ship_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    planned_delivery_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    planned_delivery_at: {
                    ...where.planned_delivery_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.shipping_costRange) {
                const [start, end] = filter.shipping_costRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    shipping_cost: {
                    ...where.shipping_cost,
                            [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.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,
                        },
                    };
                }
            }
        }
        

        

        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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'deliveries',
                        'delivery_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

