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

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

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

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

        
        await product_color_sets.setColors(data.colors || [], {
            transaction,
        });
        

        

        return product_color_sets;
    }
    

    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_color_setsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                set_name: item.set_name
            ||
            null
            ,
            
                total_colors: item.total_colors
            ||
            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_color_sets = await db.product_color_sets.bulkCreate(product_color_setsData, { transaction });

        // For each item created, replace relation files
        

        return product_color_sets;
    }

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

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


        

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

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

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

        
        
        if (data.colors !== undefined) {
            await product_color_sets.setColors(data.colors, { transaction });
        }
        

        

        return product_color_sets;
    }

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

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

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


        return product_color_sets;
    }

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

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

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

        await product_color_sets.destroy({
            transaction
        });

        return product_color_sets;
    }

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

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

        if (!product_color_sets) {
            return product_color_sets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.product = await product_color_sets.getProduct({
            transaction
        });
        
        
        output.colors = await product_color_sets.getColors({
            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.paint_colors,
        as: 'colors',
        required: false,
      },


    ];

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

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

            
            

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

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

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

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

            


      


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

        include = [
          {
            model: db.paint_colors,
            as: 'colors_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_color_sets.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_color_sets',
                        'set_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

