
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
            ,
            
        variant_sku: data.variant_sku
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        compare_at_price: data.compare_at_price
        ||
        null
            ,
            
        stock_quantity: data.stock_quantity
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        
        await product_variants.setAttributes(data.attributes || [], {
            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
            ,
            
                variant_sku: item.variant_sku
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                compare_at_price: item.compare_at_price
            ||
            null
            ,
            
                stock_quantity: item.stock_quantity
            ||
            null
            ,
            
                active: item.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.variant_sku !== undefined) updatePayload.variant_sku = data.variant_sku;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.compare_at_price !== undefined) updatePayload.compare_at_price = data.compare_at_price;
        
        
        if (data.stock_quantity !== undefined) updatePayload.stock_quantity = data.stock_quantity;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        
        if (data.attributes !== undefined) {
            await product_variants.setAttributes(data.attributes, { 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.variant_attributes_variant = await product_variants.getVariant_attributes_variant({
            transaction
        });
        
        
        
        
        
        
        
        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
        });
        
        
        output.attributes = await product_variants.getAttributes({
            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)) } },
            {
              product_name: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.variant_attributes,
        as: 'attributes',
        required: false,
      },


    ];

        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.variant_sku) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'product_variants',
                        'variant_sku',
                        filter.variant_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.compare_at_priceRange) {
                const [start, end] = filter.compare_at_priceRange;

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

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

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

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

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

            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            


      


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

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

    
};

