
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,
        
        case_price: data.case_price
        ||
        null
            ,
            
        unit_price: data.unit_price
        ||
        null
            ,
            
        min_case_qty: data.min_case_qty
        ||
        null
            ,
            
        effective_start: data.effective_start
        ||
        null
            ,
            
        effective_end: data.effective_end
        ||
        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,
        });
        

        

        

        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,
                
                case_price: item.case_price
            ||
            null
            ,
            
                unit_price: item.unit_price
            ||
            null
            ,
            
                min_case_qty: item.min_case_qty
            ||
            null
            ,
            
                effective_start: item.effective_start
            ||
            null
            ,
            
                effective_end: item.effective_end
            ||
            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 price_list_items = await db.price_list_items.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.case_price !== undefined) updatePayload.case_price = data.case_price;
        
        
        if (data.unit_price !== undefined) updatePayload.unit_price = data.unit_price;
        
        
        if (data.min_case_qty !== undefined) updatePayload.min_case_qty = data.min_case_qty;
        
        
        if (data.effective_start !== undefined) updatePayload.effective_start = data.effective_start;
        
        
        if (data.effective_end !== undefined) updatePayload.effective_end = data.effective_end;
        
        
        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 }
            );
        }
        

        
        

        

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

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        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)) } },
            {
              price_list_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)) } },
            {
              product_name: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      



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

        

        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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'price_list_items',
                        'min_case_qty',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

