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

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

        const sales_orders = await db.sales_orders.create(
            {
                id: data.id || undefined,
        
        so_number: data.so_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        order_date: data.order_date
        ||
        null
            ,
            
        requested_ship_at: data.requested_ship_at
        ||
        null
            ,
            
        promised_ship_at: data.promised_ship_at
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        subtotal: data.subtotal
        ||
        null
            ,
            
        tax_total: data.tax_total
        ||
        null
            ,
            
        total: data.total
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sales_orders.setCustomer( data.customer || null, {
            transaction,
        });
        
        await sales_orders.setSales_rep( data.sales_rep || null, {
            transaction,
        });
        

        

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

        return sales_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 sales_ordersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                so_number: item.so_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                order_date: item.order_date
            ||
            null
            ,
            
                requested_ship_at: item.requested_ship_at
            ||
            null
            ,
            
                promised_ship_at: item.promised_ship_at
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                subtotal: item.subtotal
            ||
            null
            ,
            
                tax_total: item.tax_total
            ||
            null
            ,
            
                total: item.total
            ||
            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 sales_orders = await db.sales_orders.bulkCreate(sales_ordersData, { transaction });

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

        return sales_orders;
    }

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

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


        

        const updatePayload = {};
        
        if (data.so_number !== undefined) updatePayload.so_number = data.so_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.order_date !== undefined) updatePayload.order_date = data.order_date;
        
        
        if (data.requested_ship_at !== undefined) updatePayload.requested_ship_at = data.requested_ship_at;
        
        
        if (data.promised_ship_at !== undefined) updatePayload.promised_ship_at = data.promised_ship_at;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
        
        
        if (data.tax_total !== undefined) updatePayload.tax_total = data.tax_total;
        
        
        if (data.total !== undefined) updatePayload.total = data.total;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.customer !== undefined) {
            await sales_orders.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.sales_rep !== undefined) {
            await sales_orders.setSales_rep(
              
              data.sales_rep,
              
              { transaction }
            );
        }
        

        
        

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

        return sales_orders;
    }

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

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

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


        return sales_orders;
    }

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

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

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

        await sales_orders.destroy({
            transaction
        });

        return sales_orders;
    }

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

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

        if (!sales_orders) {
            return sales_orders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sales_order_lines_sales_order = await sales_orders.getSales_order_lines_sales_order({
            transaction
        });
        
        
        output.shipments_sales_order = await sales_orders.getShipments_sales_order({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.customer = await sales_orders.getCustomer({
            transaction
        });
        
        
        output.sales_rep = await sales_orders.getSales_rep({
            transaction
        });
        
        
        output.attachments = await sales_orders.getAttachments({
            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.customers,
        as: 'customer',
        
        where: filter.customer ? {
          [Op.or]: [
            { id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.so_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales_orders',
                        'so_number',
                        filter.so_number,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales_orders',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales_orders',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total: {
                    ...where.total,
                            [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.sales_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(
                        'sales_orders',
                        'so_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

