
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
            ,
            
        order_date: data.order_date
        ||
        null
            ,
            
        expected_delivery_date: data.expected_delivery_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        subtotal_ht: data.subtotal_ht
        ||
        null
            ,
            
        tax_total: data.tax_total
        ||
        null
            ,
            
        total_ttc: data.total_ttc
        ||
        null
            ,
            
        stock_reserved: data.stock_reserved
        ||
        false
        
            ,
            
        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.setClient( data.client || null, {
            transaction,
        });
        
        await sales_orders.setSource_quote( data.source_quote || null, {
            transaction,
        });
        
        await sales_orders.setWarehouse( data.warehouse || null, {
            transaction,
        });
        
        await sales_orders.setPayment_terms( data.payment_terms || 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
            ,
            
                order_date: item.order_date
            ||
            null
            ,
            
                expected_delivery_date: item.expected_delivery_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                subtotal_ht: item.subtotal_ht
            ||
            null
            ,
            
                tax_total: item.tax_total
            ||
            null
            ,
            
                total_ttc: item.total_ttc
            ||
            null
            ,
            
                stock_reserved: item.stock_reserved
            ||
            false
        
            ,
            
                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.order_date !== undefined) updatePayload.order_date = data.order_date;
        
        
        if (data.expected_delivery_date !== undefined) updatePayload.expected_delivery_date = data.expected_delivery_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.subtotal_ht !== undefined) updatePayload.subtotal_ht = data.subtotal_ht;
        
        
        if (data.tax_total !== undefined) updatePayload.tax_total = data.tax_total;
        
        
        if (data.total_ttc !== undefined) updatePayload.total_ttc = data.total_ttc;
        
        
        if (data.stock_reserved !== undefined) updatePayload.stock_reserved = data.stock_reserved;
        
        
        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.client !== undefined) {
            await sales_orders.setClient(
              
              data.client,
              
              { transaction }
            );
        }
        
        if (data.source_quote !== undefined) {
            await sales_orders.setSource_quote(
              
              data.source_quote,
              
              { transaction }
            );
        }
        
        if (data.warehouse !== undefined) {
            await sales_orders.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        
        if (data.payment_terms !== undefined) {
            await sales_orders.setPayment_terms(
              
              data.payment_terms,
              
              { 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_items_sales_order = await sales_orders.getSales_order_items_sales_order({
            transaction
        });
        
        
        output.delivery_notes_sales_order = await sales_orders.getDelivery_notes_sales_order({
            transaction
        });
        
        
        
        output.invoices_sales_order = await sales_orders.getInvoices_sales_order({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.stock_reservations_sales_order = await sales_orders.getStock_reservations_sales_order({
            transaction
        });
        
        
        
        
        
        
        
        
        output.organization = await sales_orders.getOrganization({
            transaction
        });
        
        
        output.client = await sales_orders.getClient({
            transaction
        });
        
        
        output.source_quote = await sales_orders.getSource_quote({
            transaction
        });
        
        
        output.warehouse = await sales_orders.getWarehouse({
            transaction
        });
        
        
        output.payment_terms = await sales_orders.getPayment_terms({
            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.clients,
        as: 'client',
        
        where: filter.client ? {
          [Op.or]: [
            { id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
            {
              display_name: {
                [Op.or]: filter.client.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.quotes,
        as: 'source_quote',
        
        where: filter.source_quote ? {
          [Op.or]: [
            { id: { [Op.in]: filter.source_quote.split('|').map(term => Utils.uuid(term)) } },
            {
              quote_number: {
                [Op.or]: filter.source_quote.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.payment_terms,
        as: 'payment_terms',
        
        where: filter.payment_terms ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payment_terms.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.payment_terms.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.expected_delivery_dateRange) {
                const [start, end] = filter.expected_delivery_dateRange;

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

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

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

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

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

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


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

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

    
};

