
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
            ,
            
        shipped_at: data.shipped_at
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        subtotal: data.subtotal
        ||
        null
            ,
            
        tax_total: data.tax_total
        ||
        null
            ,
            
        total: data.total
        ||
        null
            ,
            
        shipping_address: data.shipping_address
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sales_orders.setTenant( data.tenant || null, {
            transaction,
        });
        
        await sales_orders.setCustomer( data.customer || null, {
            transaction,
        });
        
        await sales_orders.setQuotation( data.quotation || null, {
            transaction,
        });
        
        await sales_orders.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await sales_orders.setLines(data.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
            ,
            
                shipped_at: item.shipped_at
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                subtotal: item.subtotal
            ||
            null
            ,
            
                tax_total: item.tax_total
            ||
            null
            ,
            
                total: item.total
            ||
            null
            ,
            
                shipping_address: item.shipping_address
            ||
            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.shipped_at !== undefined) updatePayload.shipped_at = data.shipped_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.shipping_address !== undefined) updatePayload.shipping_address = data.shipping_address;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await sales_orders.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await sales_orders.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.quotation !== undefined) {
            await sales_orders.setQuotation(
              
              data.quotation,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await sales_orders.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.lines !== undefined) {
            await sales_orders.setLines(data.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.invoices_sales_order = await sales_orders.getInvoices_sales_order({
            transaction
        });
        
        
        
        output.customer_returns_sales_order = await sales_orders.getCustomer_returns_sales_order({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await sales_orders.getTenant({
            transaction
        });
        
        
        output.customer = await sales_orders.getCustomer({
            transaction
        });
        
        
        output.quotation = await sales_orders.getQuotation({
            transaction
        });
        
        
        output.lines = await sales_orders.getLines({
            transaction
        });
        
        
        output.organizations = await sales_orders.getOrganizations({
            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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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


      {
        model: db.sales_order_lines,
        as: '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.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales_orders',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.shipping_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales_orders',
                        'shipping_address',
                        filter.shipping_address,
                    ),
                };
            }
            
            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.shipped_atRange) {
                const [start, end] = filter.shipped_atRange;

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

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

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


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

        include = [
          {
            model: db.sales_order_lines,
            as: '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,
        }));
    }

    
};

