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

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

        const sales_order_items = await db.sales_order_items.create(
            {
                id: data.id || undefined,
        
        designation: data.designation
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        unit_label: data.unit_label
        ||
        null
            ,
            
        unit_price_ht: data.unit_price_ht
        ||
        null
            ,
            
        discount_percent: data.discount_percent
        ||
        null
            ,
            
        tax_rate_percent: data.tax_rate_percent
        ||
        null
            ,
            
        line_total_ht: data.line_total_ht
        ||
        null
            ,
            
        line_tax_total: data.line_tax_total
        ||
        null
            ,
            
        line_total_ttc: data.line_total_ttc
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sales_order_items.setSales_order( data.sales_order || null, {
            transaction,
        });
        
        await sales_order_items.setProduct( data.product || null, {
            transaction,
        });
        
        await sales_order_items.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return sales_order_items;
    }
    

    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_order_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                designation: item.designation
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                unit_label: item.unit_label
            ||
            null
            ,
            
                unit_price_ht: item.unit_price_ht
            ||
            null
            ,
            
                discount_percent: item.discount_percent
            ||
            null
            ,
            
                tax_rate_percent: item.tax_rate_percent
            ||
            null
            ,
            
                line_total_ht: item.line_total_ht
            ||
            null
            ,
            
                line_tax_total: item.line_tax_total
            ||
            null
            ,
            
                line_total_ttc: item.line_total_ttc
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const sales_order_items = await db.sales_order_items.bulkCreate(sales_order_itemsData, { transaction });

        // For each item created, replace relation files
        

        return sales_order_items;
    }

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


        

        const updatePayload = {};
        
        if (data.designation !== undefined) updatePayload.designation = data.designation;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.unit_label !== undefined) updatePayload.unit_label = data.unit_label;
        
        
        if (data.unit_price_ht !== undefined) updatePayload.unit_price_ht = data.unit_price_ht;
        
        
        if (data.discount_percent !== undefined) updatePayload.discount_percent = data.discount_percent;
        
        
        if (data.tax_rate_percent !== undefined) updatePayload.tax_rate_percent = data.tax_rate_percent;
        
        
        if (data.line_total_ht !== undefined) updatePayload.line_total_ht = data.line_total_ht;
        
        
        if (data.line_tax_total !== undefined) updatePayload.line_tax_total = data.line_tax_total;
        
        
        if (data.line_total_ttc !== undefined) updatePayload.line_total_ttc = data.line_total_ttc;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.sales_order !== undefined) {
            await sales_order_items.setSales_order(
              
              data.sales_order,
              
              { transaction }
            );
        }
        
        if (data.product !== undefined) {
            await sales_order_items.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await sales_order_items.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return sales_order_items;
    }

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

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

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


        return sales_order_items;
    }

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

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

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

        await sales_order_items.destroy({
            transaction
        });

        return sales_order_items;
    }

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

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

        if (!sales_order_items) {
            return sales_order_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sales_order = await sales_order_items.getSales_order({
            transaction
        });
        
        
        output.product = await sales_order_items.getProduct({
            transaction
        });
        
        
        output.organizations = await sales_order_items.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.sales_orders,
        as: 'sales_order',
        
        where: filter.sales_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.sales_order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.sales_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.designation) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales_order_items',
                        'designation',
                        filter.designation,
                    ),
                };
            }
            
            if (filter.unit_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales_order_items',
                        'unit_label',
                        filter.unit_label,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    line_total_ttc: {
                    ...where.line_total_ttc,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            


      

      

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

        where = {
          ...where,
          organizationsId: {[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_order_items.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_order_items',
                        'designation',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

