
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
            ,
            
        requested_ship_date: data.requested_ship_date
        ||
        null
            ,
            
        promised_ship_date: data.promised_ship_date
        ||
        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.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await sales_orders.setCustomer( data.customer || null, {
            transaction,
        });
        
        await sales_orders.setWarehouse( data.warehouse || null, {
            transaction,
        });
        
        await sales_orders.setPrice_list( data.price_list || null, {
            transaction,
        });
        

        
        await sales_orders.setSales_order_lines(data.sales_order_lines || [], {
            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
            ,
            
                requested_ship_date: item.requested_ship_date
            ||
            null
            ,
            
                promised_ship_date: item.promised_ship_date
            ||
            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
        

        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.requested_ship_date !== undefined) updatePayload.requested_ship_date = data.requested_ship_date;
        
        
        if (data.promised_ship_date !== undefined) updatePayload.promised_ship_date = data.promised_ship_date;
        
        
        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.organization !== undefined) {
            await sales_orders.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await sales_orders.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.warehouse !== undefined) {
            await sales_orders.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        
        if (data.price_list !== undefined) {
            await sales_orders.setPrice_list(
              
              data.price_list,
              
              { transaction }
            );
        }
        

        
        
        if (data.sales_order_lines !== undefined) {
            await sales_orders.setSales_order_lines(data.sales_order_lines, { 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.shipments_sales_order = await sales_orders.getShipments_sales_order({
            transaction
        });
        
        
        
        output.invoices_sales_order = await sales_orders.getInvoices_sales_order({
            transaction
        });
        
        
        
        
        
        output.organization = await sales_orders.getOrganization({
            transaction
        });
        
        
        output.customer = await sales_orders.getCustomer({
            transaction
        });
        
        
        output.warehouse = await sales_orders.getWarehouse({
            transaction
        });
        
        
        output.price_list = await sales_orders.getPrice_list({
            transaction
        });
        
        
        output.sales_order_lines = await sales_orders.getSales_order_lines({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.organizations,
        as: 'organization',
        
      },

      {
        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.warehouses,
        as: 'warehouse',
        
        where: filter.warehouse ? {
          [Op.or]: [
            { id: { [Op.in]: filter.warehouse.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.warehouse.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.sales_order_lines,
        as: 'sales_order_lines',
        required: false,
      },


    ];

        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.requested_ship_dateRange) {
                const [start, end] = filter.requested_ship_dateRange;

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    promised_ship_date: {
                    ...where.promised_ship_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.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.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[Op.or]: listItems}
        };
      }
      

      

      

      


      if (filter.sales_order_lines) {
        const searchTerms = filter.sales_order_lines.split('|');

        include = [
          {
            model: db.sales_order_lines,
            as: 'sales_order_lines_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  description: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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.organizationsId;
        }
        

        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,
        }));
    }

    
};

