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

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

        const variant_options = await db.variant_options.create(
            {
                id: data.id || undefined,
        
        option_name: data.option_name
        ||
        null
            ,
            
        option_value: data.option_value
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await variant_options.setProduct_variant( data.product_variant || null, {
            transaction,
        });
        

        

        

        return variant_options;
    }
    

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

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

        // For each item created, replace relation files
        

        return variant_options;
    }

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

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


        

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

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

        
        
        if (data.product_variant !== undefined) {
            await variant_options.setProduct_variant(
              
              data.product_variant,
              
              { transaction }
            );
        }
        

        
        

        

        return variant_options;
    }

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

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

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


        return variant_options;
    }

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

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

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

        await variant_options.destroy({
            transaction
        });

        return variant_options;
    }

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

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

        if (!variant_options) {
            return variant_options;
        }

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

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



    ];

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

            
            if (filter.option_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'variant_options',
                        'option_name',
                        filter.option_name,
                    ),
                };
            }
            
            if (filter.option_value) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'variant_options',
                        'option_value',
                        filter.option_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_options.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_options',
                        'option_value',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

