
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,
        
        order_number: data.order_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        order_date: data.order_date
        ||
        null
            ,
            
        due_date: data.due_date
        ||
        null
            ,
            
        subtotal_amount: data.subtotal_amount
        ||
        null
            ,
            
        discount_amount: data.discount_amount
        ||
        null
            ,
            
        tax_amount: data.tax_amount
        ||
        null
            ,
            
        shipping_amount: data.shipping_amount
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        payment_status: data.payment_status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sales_orders.setCompany( data.company || null, {
            transaction,
        });
        
        await sales_orders.setBusiness_unit( data.business_unit || null, {
            transaction,
        });
        
        await sales_orders.setCustomer( data.customer || null, {
            transaction,
        });
        

        

        

        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,
                
                order_number: item.order_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                order_date: item.order_date
            ||
            null
            ,
            
                due_date: item.due_date
            ||
            null
            ,
            
                subtotal_amount: item.subtotal_amount
            ||
            null
            ,
            
                discount_amount: item.discount_amount
            ||
            null
            ,
            
                tax_amount: item.tax_amount
            ||
            null
            ,
            
                shipping_amount: item.shipping_amount
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                payment_status: item.payment_status
            ||
            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
        

        return sales_orders;
    }

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


        

        const updatePayload = {};
        
        if (data.order_number !== undefined) updatePayload.order_number = data.order_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.order_date !== undefined) updatePayload.order_date = data.order_date;
        
        
        if (data.due_date !== undefined) updatePayload.due_date = data.due_date;
        
        
        if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
        
        
        if (data.discount_amount !== undefined) updatePayload.discount_amount = data.discount_amount;
        
        
        if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
        
        
        if (data.shipping_amount !== undefined) updatePayload.shipping_amount = data.shipping_amount;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.payment_status !== undefined) updatePayload.payment_status = data.payment_status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await sales_orders.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.business_unit !== undefined) {
            await sales_orders.setBusiness_unit(
              
              data.business_unit,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await sales_orders.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        

        
        

        

        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.invoices_sales_order = await sales_orders.getInvoices_sales_order({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await sales_orders.getCompany({
            transaction
        });
        
        
        output.business_unit = await sales_orders.getBusiness_unit({
            transaction
        });
        
        
        output.customer = await sales_orders.getCustomer({
            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 userCompanies = (user && user.companies?.id) || null;
        

        
        if (userCompanies) {
            if (options?.currentUser?.companiesId) {
                where.companiesId = options.currentUser.companiesId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.companies,
        as: 'company',
        
      },

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

      {
        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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.order_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales_orders',
                        'order_number',
                        filter.order_number,
                    ),
                };
            }
            
            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.due_dateRange) {
                const [start, end] = filter.due_dateRange;

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

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

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

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

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

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

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

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

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

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

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

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


      
      if (filter.company) {
        const listItems = filter.company.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          companyId: {[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.companiesId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

        const records = await db.sales_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,
        }));
    }

    
};

