
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_title: data.variant_title
        ||
        null
            ,
            
        sku: data.sku
        ||
        null
            ,
            
        barcode: data.barcode
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        compare_at_price: data.compare_at_price
        ||
        null
            ,
            
        inventory_quantity: data.inventory_quantity
        ||
        null
            ,
            
        inventory_policy: data.inventory_policy
        ||
        null
            ,
            
        taxable: data.taxable
        ||
        false
        
            ,
            
        weight: data.weight
        ||
        null
            ,
            
        weight_unit: data.weight_unit
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await product_variants.setProduct( data.product || null, {
            transaction,
        });
        
        await product_variants.setOrganizations( data.organizations || 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_title: item.variant_title
            ||
            null
            ,
            
                sku: item.sku
            ||
            null
            ,
            
                barcode: item.barcode
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                compare_at_price: item.compare_at_price
            ||
            null
            ,
            
                inventory_quantity: item.inventory_quantity
            ||
            null
            ,
            
                inventory_policy: item.inventory_policy
            ||
            null
            ,
            
                taxable: item.taxable
            ||
            false
        
            ,
            
                weight: item.weight
            ||
            null
            ,
            
                weight_unit: item.weight_unit
            ||
            null
            ,
            
            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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.variant_title !== undefined) updatePayload.variant_title = data.variant_title;
        
        
        if (data.sku !== undefined) updatePayload.sku = data.sku;
        
        
        if (data.barcode !== undefined) updatePayload.barcode = data.barcode;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.compare_at_price !== undefined) updatePayload.compare_at_price = data.compare_at_price;
        
        
        if (data.inventory_quantity !== undefined) updatePayload.inventory_quantity = data.inventory_quantity;
        
        
        if (data.inventory_policy !== undefined) updatePayload.inventory_policy = data.inventory_policy;
        
        
        if (data.taxable !== undefined) updatePayload.taxable = data.taxable;
        
        
        if (data.weight !== undefined) updatePayload.weight = data.weight;
        
        
        if (data.weight_unit !== undefined) updatePayload.weight_unit = data.weight_unit;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.product !== undefined) {
            await product_variants.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await product_variants.setOrganizations(
              
              data.organizations,
              
              { 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.order_items_variant = await product_variants.getOrder_items_variant({
            transaction
        });
        
        
        
        
        
        
        output.inventory_adjustments_variant = await product_variants.getInventory_adjustments_variant({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.product = await product_variants.getProduct({
            transaction
        });
        
        
        output.organizations = await product_variants.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        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_title: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

            
            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.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.weightRange) {
                const [start, end] = filter.weightRange;

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

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

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

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


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'product_variants',
                        'variant_title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

