
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,
        
        name_ar: data.name_ar
        ||
        null
            ,
            
        name_en: data.name_en
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        short_description_ar: data.short_description_ar
        ||
        null
            ,
            
        short_description_en: data.short_description_en
        ||
        null
            ,
            
        description_ar: data.description_ar
        ||
        null
            ,
            
        description_en: data.description_en
        ||
        null
            ,
            
        sku: data.sku
        ||
        null
            ,
            
        barcode: data.barcode
        ||
        null
            ,
            
        price_iqd: data.price_iqd
        ||
        null
            ,
            
        compare_at_price_iqd: data.compare_at_price_iqd
        ||
        null
            ,
            
        cost_iqd: data.cost_iqd
        ||
        null
            ,
            
        stock_on_hand: data.stock_on_hand
        ||
        null
            ,
            
        low_stock_threshold: data.low_stock_threshold
        ||
        null
            ,
            
        track_inventory: data.track_inventory
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        is_featured: data.is_featured
        ||
        false
        
            ,
            
        condition: data.condition
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        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 products.setSupplier( data.supplier || null, {
            transaction,
        });
        

        
        await products.setVariants(data.variants || [], {
            transaction,
        });
        
        await products.setReviews(data.reviews || [], {
            transaction,
        });
        
        await products.setCollections(data.collections || [], {
            transaction,
        });
        
        await products.setFbt_items(data.fbt_items || [], {
            transaction,
        });
        
        await products.setSeo_entries(data.seo_entries || [], {
            transaction,
        });
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'images',
                belongsToId: products.id,
            },
            data.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,
                
                name_ar: item.name_ar
            ||
            null
            ,
            
                name_en: item.name_en
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                short_description_ar: item.short_description_ar
            ||
            null
            ,
            
                short_description_en: item.short_description_en
            ||
            null
            ,
            
                description_ar: item.description_ar
            ||
            null
            ,
            
                description_en: item.description_en
            ||
            null
            ,
            
                sku: item.sku
            ||
            null
            ,
            
                barcode: item.barcode
            ||
            null
            ,
            
                price_iqd: item.price_iqd
            ||
            null
            ,
            
                compare_at_price_iqd: item.compare_at_price_iqd
            ||
            null
            ,
            
                cost_iqd: item.cost_iqd
            ||
            null
            ,
            
                stock_on_hand: item.stock_on_hand
            ||
            null
            ,
            
                low_stock_threshold: item.low_stock_threshold
            ||
            null
            ,
            
                track_inventory: item.track_inventory
            ||
            false
        
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                is_featured: item.is_featured
            ||
            false
        
            ,
            
                condition: item.condition
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            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: 'images',
                    belongsToId: products[i].id,
                },
                data[i].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.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
        
        
        if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.short_description_ar !== undefined) updatePayload.short_description_ar = data.short_description_ar;
        
        
        if (data.short_description_en !== undefined) updatePayload.short_description_en = data.short_description_en;
        
        
        if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
        
        
        if (data.description_en !== undefined) updatePayload.description_en = data.description_en;
        
        
        if (data.sku !== undefined) updatePayload.sku = data.sku;
        
        
        if (data.barcode !== undefined) updatePayload.barcode = data.barcode;
        
        
        if (data.price_iqd !== undefined) updatePayload.price_iqd = data.price_iqd;
        
        
        if (data.compare_at_price_iqd !== undefined) updatePayload.compare_at_price_iqd = data.compare_at_price_iqd;
        
        
        if (data.cost_iqd !== undefined) updatePayload.cost_iqd = data.cost_iqd;
        
        
        if (data.stock_on_hand !== undefined) updatePayload.stock_on_hand = data.stock_on_hand;
        
        
        if (data.low_stock_threshold !== undefined) updatePayload.low_stock_threshold = data.low_stock_threshold;
        
        
        if (data.track_inventory !== undefined) updatePayload.track_inventory = data.track_inventory;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
        
        
        if (data.condition !== undefined) updatePayload.condition = data.condition;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        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 }
            );
        }
        
        if (data.supplier !== undefined) {
            await products.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        

        
        
        if (data.variants !== undefined) {
            await products.setVariants(data.variants, { transaction });
        }
        
        if (data.reviews !== undefined) {
            await products.setReviews(data.reviews, { transaction });
        }
        
        if (data.collections !== undefined) {
            await products.setCollections(data.collections, { transaction });
        }
        
        if (data.fbt_items !== undefined) {
            await products.setFbt_items(data.fbt_items, { transaction });
        }
        
        if (data.seo_entries !== undefined) {
            await products.setSeo_entries(data.seo_entries, { transaction });
        }
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'images',
                belongsToId: products.id,
            },
            data.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_reviews_product = await products.getProduct_reviews_product({
            transaction
        });
        
        
        output.wishlist_items_product = await products.getWishlist_items_product({
            transaction
        });
        
        
        
        output.compare_items_product = await products.getCompare_items_product({
            transaction
        });
        
        
        
        output.cart_items_product = await products.getCart_items_product({
            transaction
        });
        
        
        
        output.order_items_product = await products.getOrder_items_product({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.frequently_bought_together_groups_primary_product = await products.getFrequently_bought_together_groups_primary_product({
            transaction
        });
        
        
        output.frequently_bought_together_items_product = await products.getFrequently_bought_together_items_product({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.images = await products.getImages({
            transaction
        });
        
        
        output.category = await products.getCategory({
            transaction
        });
        
        
        output.brand = await products.getBrand({
            transaction
        });
        
        
        output.supplier = await products.getSupplier({
            transaction
        });
        
        
        output.variants = await products.getVariants({
            transaction
        });
        
        
        output.reviews = await products.getReviews({
            transaction
        });
        
        
        output.collections = await products.getCollections({
            transaction
        });
        
        
        output.fbt_items = await products.getFbt_items({
            transaction
        });
        
        
        output.seo_entries = await products.getSeo_entries({
            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.categories,
        as: 'category',
        
        where: filter.category ? {
          [Op.or]: [
            { id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
            {
              name_ar: {
                [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.suppliers,
        as: 'supplier',
        
        where: filter.supplier ? {
          [Op.or]: [
            { id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.product_variants,
        as: 'variants',
        required: false,
      },

      {
        model: db.product_reviews,
        as: 'reviews',
        required: false,
      },

      {
        model: db.collections,
        as: 'collections',
        required: false,
      },

      {
        model: db.frequently_bought_together_items,
        as: 'fbt_items',
        required: false,
      },

      {
        model: db.seo_entries,
        as: 'seo_entries',
        required: false,
      },


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

    ];

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

            
            if (filter.name_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'name_ar',
                        filter.name_ar,
                    ),
                };
            }
            
            if (filter.name_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'name_en',
                        filter.name_en,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.short_description_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'short_description_ar',
                        filter.short_description_ar,
                    ),
                };
            }
            
            if (filter.short_description_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'short_description_en',
                        filter.short_description_en,
                    ),
                };
            }
            
            if (filter.description_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'description_ar',
                        filter.description_ar,
                    ),
                };
            }
            
            if (filter.description_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'description_en',
                        filter.description_en,
                    ),
                };
            }
            
            if (filter.sku) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'sku',
                        filter.sku,
                    ),
                };
            }
            
            if (filter.barcode) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'barcode',
                        filter.barcode,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.track_inventory) {
                where = {
                    ...where,
                track_inventory: filter.track_inventory,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            
            if (filter.is_featured) {
                where = {
                    ...where,
                is_featured: filter.is_featured,
            };
            }
            
            if (filter.condition) {
                where = {
                    ...where,
                condition: filter.condition,
            };
            }
            


      

      

      


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

        include = [
          {
            model: db.product_variants,
            as: 'variants_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

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

        include = [
          {
            model: db.product_reviews,
            as: 'reviews_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  title: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

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

        include = [
          {
            model: db.collections,
            as: 'collections_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name_ar: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

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

        include = [
          {
            model: db.frequently_bought_together_items,
            as: 'fbt_items_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  sort_order: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

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

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

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

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

    
};

