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

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

        const orders = await db.orders.create(
            {
                id: data.id || undefined,
        
        order_number: data.order_number
        ||
        null
            ,
            
        po_number: data.po_number
        ||
        null
            ,
            
        ordered_at: data.ordered_at
        ||
        null
            ,
            
        requested_delivery_date: data.requested_delivery_date
        ||
        null
            ,
            
        promised_delivery_date: data.promised_delivery_date
        ||
        null
            ,
            
        order_status: data.order_status
        ||
        null
            ,
            
        payment_terms: data.payment_terms
        ||
        null
            ,
            
        subtotal: data.subtotal
        ||
        null
            ,
            
        tax_total: data.tax_total
        ||
        null
            ,
            
        shipping_total: data.shipping_total
        ||
        null
            ,
            
        order_total: data.order_total
        ||
        null
            ,
            
        buyer_notes: data.buyer_notes
        ||
        null
            ,
            
        internal_notes: data.internal_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await orders.setAccount( data.account || null, {
            transaction,
        });
        
        await orders.setLocation( data.location || null, {
            transaction,
        });
        
        await orders.setBuyer( data.buyer || null, {
            transaction,
        });
        

        

        

        return orders;
    }
    

    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 ordersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                order_number: item.order_number
            ||
            null
            ,
            
                po_number: item.po_number
            ||
            null
            ,
            
                ordered_at: item.ordered_at
            ||
            null
            ,
            
                requested_delivery_date: item.requested_delivery_date
            ||
            null
            ,
            
                promised_delivery_date: item.promised_delivery_date
            ||
            null
            ,
            
                order_status: item.order_status
            ||
            null
            ,
            
                payment_terms: item.payment_terms
            ||
            null
            ,
            
                subtotal: item.subtotal
            ||
            null
            ,
            
                tax_total: item.tax_total
            ||
            null
            ,
            
                shipping_total: item.shipping_total
            ||
            null
            ,
            
                order_total: item.order_total
            ||
            null
            ,
            
                buyer_notes: item.buyer_notes
            ||
            null
            ,
            
                internal_notes: item.internal_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return orders;
    }

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

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


        

        const updatePayload = {};
        
        if (data.order_number !== undefined) updatePayload.order_number = data.order_number;
        
        
        if (data.po_number !== undefined) updatePayload.po_number = data.po_number;
        
        
        if (data.ordered_at !== undefined) updatePayload.ordered_at = data.ordered_at;
        
        
        if (data.requested_delivery_date !== undefined) updatePayload.requested_delivery_date = data.requested_delivery_date;
        
        
        if (data.promised_delivery_date !== undefined) updatePayload.promised_delivery_date = data.promised_delivery_date;
        
        
        if (data.order_status !== undefined) updatePayload.order_status = data.order_status;
        
        
        if (data.payment_terms !== undefined) updatePayload.payment_terms = data.payment_terms;
        
        
        if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
        
        
        if (data.tax_total !== undefined) updatePayload.tax_total = data.tax_total;
        
        
        if (data.shipping_total !== undefined) updatePayload.shipping_total = data.shipping_total;
        
        
        if (data.order_total !== undefined) updatePayload.order_total = data.order_total;
        
        
        if (data.buyer_notes !== undefined) updatePayload.buyer_notes = data.buyer_notes;
        
        
        if (data.internal_notes !== undefined) updatePayload.internal_notes = data.internal_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.account !== undefined) {
            await orders.setAccount(
              
              data.account,
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await orders.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.buyer !== undefined) {
            await orders.setBuyer(
              
              data.buyer,
              
              { transaction }
            );
        }
        

        
        

        

        return orders;
    }

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

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

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


        return orders;
    }

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

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

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

        await orders.destroy({
            transaction
        });

        return orders;
    }

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

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

        if (!orders) {
            return orders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.order_items_order = await orders.getOrder_items_order({
            transaction
        });
        
        
        output.shipments_order = await orders.getShipments_order({
            transaction
        });
        
        
        
        
        
        
        
        
        output.account = await orders.getAccount({
            transaction
        });
        
        
        output.location = await orders.getLocation({
            transaction
        });
        
        
        output.buyer = await orders.getBuyer({
            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.accounts,
        as: 'account',
        
        where: filter.account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.account.split('|').map(term => Utils.uuid(term)) } },
            {
              account_name: {
                [Op.or]: filter.account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.order_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'orders',
                        'order_number',
                        filter.order_number,
                    ),
                };
            }
            
            if (filter.po_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'orders',
                        'po_number',
                        filter.po_number,
                    ),
                };
            }
            
            if (filter.buyer_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'orders',
                        'buyer_notes',
                        filter.buyer_notes,
                    ),
                };
            }
            
            if (filter.internal_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'orders',
                        'internal_notes',
                        filter.internal_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.order_status) {
                where = {
                    ...where,
                order_status: filter.order_status,
            };
            }
            
            if (filter.payment_terms) {
                where = {
                    ...where,
                payment_terms: filter.payment_terms,
            };
            }
            


      

      

      



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

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

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

    
};

