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

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

        const products = await db.products.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        subtitle: data.subtitle
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        product_type: data.product_type
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        is_best_seller: data.is_best_seller
        ||
        false
        
            ,
            
        is_new_arrival: data.is_new_arrival
        ||
        false
        
            ,
            
        base_price: data.base_price
        ||
        null
            ,
            
        inventory_quantity: data.inventory_quantity
        ||
        null
            ,
            
        sku: data.sku
        ||
        null
            ,
            
        rating_average: data.rating_average
        ||
        null
            ,
            
        rating_count: data.rating_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await products.setCategory( data.category || null, {
            transaction,
        });
        
        await products.setBrand( data.brand || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'gallery_images',
                belongsToId: products.id,
            },
            data.gallery_images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'canvas_preview_images',
                belongsToId: products.id,
            },
            data.canvas_preview_images,
            options,
        );
        

        return products;
    }
    

    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 productsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                subtitle: item.subtitle
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                product_type: item.product_type
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                is_best_seller: item.is_best_seller
            ||
            false
        
            ,
            
                is_new_arrival: item.is_new_arrival
            ||
            false
        
            ,
            
                base_price: item.base_price
            ||
            null
            ,
            
                inventory_quantity: item.inventory_quantity
            ||
            null
            ,
            
                sku: item.sku
            ||
            null
            ,
            
                rating_average: item.rating_average
            ||
            null
            ,
            
                rating_count: item.rating_count
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < products.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.products.getTableName(),
                    belongsToColumn: 'gallery_images',
                    belongsToId: products[i].id,
                },
                data[i].gallery_images,
                options,
            );
        }
        
        for (let i = 0; i < products.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.products.getTableName(),
                    belongsToColumn: 'canvas_preview_images',
                    belongsToId: products[i].id,
                },
                data[i].canvas_preview_images,
                options,
            );
        }
        

        return products;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.subtitle !== undefined) updatePayload.subtitle = data.subtitle;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.product_type !== undefined) updatePayload.product_type = data.product_type;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.is_best_seller !== undefined) updatePayload.is_best_seller = data.is_best_seller;
        
        
        if (data.is_new_arrival !== undefined) updatePayload.is_new_arrival = data.is_new_arrival;
        
        
        if (data.base_price !== undefined) updatePayload.base_price = data.base_price;
        
        
        if (data.inventory_quantity !== undefined) updatePayload.inventory_quantity = data.inventory_quantity;
        
        
        if (data.sku !== undefined) updatePayload.sku = data.sku;
        
        
        if (data.rating_average !== undefined) updatePayload.rating_average = data.rating_average;
        
        
        if (data.rating_count !== undefined) updatePayload.rating_count = data.rating_count;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.category !== undefined) {
            await products.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        
        if (data.brand !== undefined) {
            await products.setBrand(
              
              data.brand,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'gallery_images',
                belongsToId: products.id,
            },
            data.gallery_images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'canvas_preview_images',
                belongsToId: products.id,
            },
            data.canvas_preview_images,
            options,
        );
        

        return products;
    }

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

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

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


        return products;
    }

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

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

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

        await products.destroy({
            transaction
        });

        return products;
    }

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

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

        if (!products) {
            return products;
        }

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

        
        
        
        
        
        
        
        output.product_variants_product = await products.getProduct_variants_product({
            transaction
        });
        
        
        
        output.product_color_sets_product = await products.getProduct_color_sets_product({
            transaction
        });
        
        
        
        output.product_brush_kits_product = await products.getProduct_brush_kits_product({
            transaction
        });
        
        
        output.reviews_product = await products.getReviews_product({
            transaction
        });
        
        
        
        output.cart_items_product = await products.getCart_items_product({
            transaction
        });
        
        
        
        output.order_items_product = await products.getOrder_items_product({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.category = await products.getCategory({
            transaction
        });
        
        
        output.brand = await products.getBrand({
            transaction
        });
        
        
        output.gallery_images = await products.getGallery_images({
            transaction
        });
        
        
        output.canvas_preview_images = await products.getCanvas_preview_images({
            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_categories,
        as: 'category',
        
        where: filter.category ? {
          [Op.or]: [
            { id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.brands,
        as: 'brand',
        
        where: filter.brand ? {
          [Op.or]: [
            { id: { [Op.in]: filter.brand.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.brand.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'gallery_images',
      },

      {
        model: db.file,
        as: 'canvas_preview_images',
      },

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.subtitle) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'subtitle',
                        filter.subtitle,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.sku) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'sku',
                        filter.sku,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    base_price: {
                    ...where.base_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.rating_averageRange) {
                const [start, end] = filter.rating_averageRange;

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

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

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

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

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

            
            if (filter.product_type) {
                where = {
                    ...where,
                product_type: filter.product_type,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            
            if (filter.is_best_seller) {
                where = {
                    ...where,
                is_best_seller: filter.is_best_seller,
            };
            }
            
            if (filter.is_new_arrival) {
                where = {
                    ...where,
                is_new_arrival: filter.is_new_arrival,
            };
            }
            


      

      



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

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

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

    
};

