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

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

        const price_list_items = await db.price_list_items.create(
            {
                id: data.id || undefined,
        
        price: data.price
        ||
        null
            ,
            
        min_quantity: data.min_quantity
        ||
        null
            ,
            
        valid_from: data.valid_from
        ||
        null
            ,
            
        valid_to: data.valid_to
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await price_list_items.setPrice_list( data.price_list || null, {
            transaction,
        });
        
        await price_list_items.setProduct( data.product || null, {
            transaction,
        });
        
        await price_list_items.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return price_list_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 price_list_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                price: item.price
            ||
            null
            ,
            
                min_quantity: item.min_quantity
            ||
            null
            ,
            
                valid_from: item.valid_from
            ||
            null
            ,
            
                valid_to: item.valid_to
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.min_quantity !== undefined) updatePayload.min_quantity = data.min_quantity;
        
        
        if (data.valid_from !== undefined) updatePayload.valid_from = data.valid_from;
        
        
        if (data.valid_to !== undefined) updatePayload.valid_to = data.valid_to;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.price_list !== undefined) {
            await price_list_items.setPrice_list(
              
              data.price_list,
              
              { transaction }
            );
        }
        
        if (data.product !== undefined) {
            await price_list_items.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await price_list_items.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return price_list_items;
    }

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

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

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


        return price_list_items;
    }

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

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

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

        await price_list_items.destroy({
            transaction
        });

        return price_list_items;
    }

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

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

        if (!price_list_items) {
            return price_list_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.price_list = await price_list_items.getPrice_list({
            transaction
        });
        
        
        output.product = await price_list_items.getProduct({
            transaction
        });
        
        
        output.organizations = await price_list_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.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.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.priceRange) {
                const [start, end] = filter.priceRange;

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    valid_to: {
                    ...where.valid_to,
                            [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.price_list_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(
                        'price_list_items',
                        'valid_from',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

