
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
            ,
            
        departed_at: data.departed_at
        ||
        null
            ,
            
        arrived_at: data.arrived_at
        ||
        null
            ,
            
        delivery_note: data.delivery_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await deliveries.setPurchase_order( data.purchase_order || null, {
            transaction,
        });
        
        await deliveries.setStore( data.store || null, {
            transaction,
        });
        
        await deliveries.setReceived_by_employee( data.received_by_employee || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.deliveries.getTableName(),
                belongsToColumn: 'delivery_documents',
                belongsToId: deliveries.id,
            },
            data.delivery_documents,
            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_status: item.delivery_status
            ||
            null
            ,
            
                departed_at: item.departed_at
            ||
            null
            ,
            
                arrived_at: item.arrived_at
            ||
            null
            ,
            
                delivery_note: item.delivery_note
            ||
            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: 'delivery_documents',
                    belongsToId: deliveries[i].id,
                },
                data[i].delivery_documents,
                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_status !== undefined) updatePayload.delivery_status = data.delivery_status;
        
        
        if (data.departed_at !== undefined) updatePayload.departed_at = data.departed_at;
        
        
        if (data.arrived_at !== undefined) updatePayload.arrived_at = data.arrived_at;
        
        
        if (data.delivery_note !== undefined) updatePayload.delivery_note = data.delivery_note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.purchase_order !== undefined) {
            await deliveries.setPurchase_order(
              
              data.purchase_order,
              
              { transaction }
            );
        }
        
        if (data.store !== undefined) {
            await deliveries.setStore(
              
              data.store,
              
              { transaction }
            );
        }
        
        if (data.received_by_employee !== undefined) {
            await deliveries.setReceived_by_employee(
              
              data.received_by_employee,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.deliveries.getTableName(),
                belongsToColumn: 'delivery_documents',
                belongsToId: deliveries.id,
            },
            data.delivery_documents,
            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.purchase_order = await deliveries.getPurchase_order({
            transaction
        });
        
        
        output.store = await deliveries.getStore({
            transaction
        });
        
        
        output.received_by_employee = await deliveries.getReceived_by_employee({
            transaction
        });
        
        
        output.delivery_documents = await deliveries.getDelivery_documents({
            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.purchase_orders,
        as: 'purchase_order',
        
        where: filter.purchase_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.purchase_order.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.purchase_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.delivery_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deliveries',
                        'delivery_note',
                        filter.delivery_note,
                    ),
                };
            }
            

            
            

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

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

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

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

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

    
};

