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

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

        const variant_attributes = await db.variant_attributes.create(
            {
                id: data.id || undefined,
        
        attribute_name: data.attribute_name
        ||
        null
            ,
            
        attribute_value: data.attribute_value
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await variant_attributes.setVariant( data.variant || null, {
            transaction,
        });
        

        

        

        return variant_attributes;
    }
    

    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 variant_attributesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                attribute_name: item.attribute_name
            ||
            null
            ,
            
                attribute_value: item.attribute_value
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return variant_attributes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.attribute_name !== undefined) updatePayload.attribute_name = data.attribute_name;
        
        
        if (data.attribute_value !== undefined) updatePayload.attribute_value = data.attribute_value;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.variant !== undefined) {
            await variant_attributes.setVariant(
              
              data.variant,
              
              { transaction }
            );
        }
        

        
        

        

        return variant_attributes;
    }

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

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

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


        return variant_attributes;
    }

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

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

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

        await variant_attributes.destroy({
            transaction
        });

        return variant_attributes;
    }

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

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

        if (!variant_attributes) {
            return variant_attributes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.variant = await variant_attributes.getVariant({
            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.product_variants,
        as: 'variant',
        
        where: filter.variant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.variant.split('|').map(term => Utils.uuid(term)) } },
            {
              variant_name: {
                [Op.or]: filter.variant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.attribute_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'variant_attributes',
                        'attribute_name',
                        filter.attribute_name,
                    ),
                };
            }
            
            if (filter.attribute_value) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'variant_attributes',
                        'attribute_value',
                        filter.attribute_value,
                    ),
                };
            }
            

            
            

            

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

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

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

    
};

