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

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

        const product_variants = await db.product_variants.create(
            {
                id: data.id || undefined,
        
        variant_name: data.variant_name
        ||
        null
            ,
            
        sku: data.sku
        ||
        null
            ,
            
        size: data.size
        ||
        null
            ,
            
        difficulty: data.difficulty
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        inventory_quantity: data.inventory_quantity
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return product_variants;
    }
    

    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_variantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                variant_name: item.variant_name
            ||
            null
            ,
            
                sku: item.sku
            ||
            null
            ,
            
                size: item.size
            ||
            null
            ,
            
                difficulty: item.difficulty
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                inventory_quantity: item.inventory_quantity
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return product_variants;
    }

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

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


        

        const updatePayload = {};
        
        if (data.variant_name !== undefined) updatePayload.variant_name = data.variant_name;
        
        
        if (data.sku !== undefined) updatePayload.sku = data.sku;
        
        
        if (data.size !== undefined) updatePayload.size = data.size;
        
        
        if (data.difficulty !== undefined) updatePayload.difficulty = data.difficulty;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.inventory_quantity !== undefined) updatePayload.inventory_quantity = data.inventory_quantity;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return product_variants;
    }

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

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

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


        return product_variants;
    }

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

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

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

        await product_variants.destroy({
            transaction
        });

        return product_variants;
    }

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

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

        if (!product_variants) {
            return product_variants;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cart_items_variant = await product_variants.getCart_items_variant({
            transaction
        });
        
        
        
        output.order_items_variant = await product_variants.getOrder_items_variant({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.product = await product_variants.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.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.variant_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'product_variants',
                        'variant_name',
                        filter.variant_name,
                    ),
                };
            }
            
            if (filter.sku) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'product_variants',
                        'sku',
                        filter.sku,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.size) {
                where = {
                    ...where,
                size: filter.size,
            };
            }
            
            if (filter.difficulty) {
                where = {
                    ...where,
                difficulty: filter.difficulty,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      



            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_variants.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_variants',
                        'variant_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

