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

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

        const product_brush_kits = await db.product_brush_kits.create(
            {
                id: data.id || undefined,
        
        kit_name: data.kit_name
        ||
        null
            ,
            
        brush_count: data.brush_count
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await product_brush_kits.setProduct( data.product || null, {
            transaction,
        });
        

        
        await product_brush_kits.setBrushes(data.brushes || [], {
            transaction,
        });
        

        

        return product_brush_kits;
    }
    

    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 product_brush_kitsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                kit_name: item.kit_name
            ||
            null
            ,
            
                brush_count: item.brush_count
            ||
            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 product_brush_kits = await db.product_brush_kits.bulkCreate(product_brush_kitsData, { transaction });

        // For each item created, replace relation files
        

        return product_brush_kits;
    }

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

        const product_brush_kits = await db.product_brush_kits.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.kit_name !== undefined) updatePayload.kit_name = data.kit_name;
        
        
        if (data.brush_count !== undefined) updatePayload.brush_count = data.brush_count;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.product !== undefined) {
            await product_brush_kits.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        

        
        
        if (data.brushes !== undefined) {
            await product_brush_kits.setBrushes(data.brushes, { transaction });
        }
        

        

        return product_brush_kits;
    }

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

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

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


        return product_brush_kits;
    }

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

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

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

        await product_brush_kits.destroy({
            transaction
        });

        return product_brush_kits;
    }

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

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

        if (!product_brush_kits) {
            return product_brush_kits;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.product = await product_brush_kits.getProduct({
            transaction
        });
        
        
        output.brushes = await product_brush_kits.getBrushes({
            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.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.brush_types,
        as: 'brushes',
        required: false,
      },


    ];

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

            
            if (filter.kit_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'product_brush_kits',
                        'kit_name',
                        filter.kit_name,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'product_brush_kits',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

            


      


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

        include = [
          {
            model: db.brush_types,
            as: 'brushes_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [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,
                        },
                    };
                }
            }
        }
        

        

        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.product_brush_kits.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(
                        'product_brush_kits',
                        'kit_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

