
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,
        
        product_name: data.product_name
        ||
        null
            ,
            
        sku: data.sku
        ||
        null
            ,
            
        barcode: data.barcode
        ||
        null
            ,
            
        product_status: data.product_status
        ||
        null
            ,
            
        brand: data.brand
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        unit: data.unit
        ||
        null
            ,
            
        weight_grams: data.weight_grams
        ||
        null
            ,
            
        length_cm: data.length_cm
        ||
        null
            ,
            
        width_cm: data.width_cm
        ||
        null
            ,
            
        height_cm: data.height_cm
        ||
        null
            ,
            
        cost_price: data.cost_price
        ||
        null
            ,
            
        retail_price: data.retail_price
        ||
        null
            ,
            
        reseller_price: data.reseller_price
        ||
        null
            ,
            
        agent_price: data.agent_price
        ||
        null
            ,
            
        distributor_price: data.distributor_price
        ||
        null
            ,
            
        low_stock_threshold: data.low_stock_threshold
        ||
        null
            ,
            
        short_description: data.short_description
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await products.setTenant( data.tenant || null, {
            transaction,
        });
        
        await products.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'product_images',
                belongsToId: products.id,
            },
            data.product_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,
                
                product_name: item.product_name
            ||
            null
            ,
            
                sku: item.sku
            ||
            null
            ,
            
                barcode: item.barcode
            ||
            null
            ,
            
                product_status: item.product_status
            ||
            null
            ,
            
                brand: item.brand
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                unit: item.unit
            ||
            null
            ,
            
                weight_grams: item.weight_grams
            ||
            null
            ,
            
                length_cm: item.length_cm
            ||
            null
            ,
            
                width_cm: item.width_cm
            ||
            null
            ,
            
                height_cm: item.height_cm
            ||
            null
            ,
            
                cost_price: item.cost_price
            ||
            null
            ,
            
                retail_price: item.retail_price
            ||
            null
            ,
            
                reseller_price: item.reseller_price
            ||
            null
            ,
            
                agent_price: item.agent_price
            ||
            null
            ,
            
                distributor_price: item.distributor_price
            ||
            null
            ,
            
                low_stock_threshold: item.low_stock_threshold
            ||
            null
            ,
            
                short_description: item.short_description
            ||
            null
            ,
            
                description: item.description
            ||
            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: 'product_images',
                    belongsToId: products[i].id,
                },
                data[i].product_images,
                options,
            );
        }
        

        return products;
    }

    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 products = await db.products.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.product_name !== undefined) updatePayload.product_name = data.product_name;
        
        
        if (data.sku !== undefined) updatePayload.sku = data.sku;
        
        
        if (data.barcode !== undefined) updatePayload.barcode = data.barcode;
        
        
        if (data.product_status !== undefined) updatePayload.product_status = data.product_status;
        
        
        if (data.brand !== undefined) updatePayload.brand = data.brand;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.unit !== undefined) updatePayload.unit = data.unit;
        
        
        if (data.weight_grams !== undefined) updatePayload.weight_grams = data.weight_grams;
        
        
        if (data.length_cm !== undefined) updatePayload.length_cm = data.length_cm;
        
        
        if (data.width_cm !== undefined) updatePayload.width_cm = data.width_cm;
        
        
        if (data.height_cm !== undefined) updatePayload.height_cm = data.height_cm;
        
        
        if (data.cost_price !== undefined) updatePayload.cost_price = data.cost_price;
        
        
        if (data.retail_price !== undefined) updatePayload.retail_price = data.retail_price;
        
        
        if (data.reseller_price !== undefined) updatePayload.reseller_price = data.reseller_price;
        
        
        if (data.agent_price !== undefined) updatePayload.agent_price = data.agent_price;
        
        
        if (data.distributor_price !== undefined) updatePayload.distributor_price = data.distributor_price;
        
        
        if (data.low_stock_threshold !== undefined) updatePayload.low_stock_threshold = data.low_stock_threshold;
        
        
        if (data.short_description !== undefined) updatePayload.short_description = data.short_description;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await products.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await products.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'product_images',
                belongsToId: products.id,
            },
            data.product_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.inventory_items_product = await products.getInventory_items_product({
            transaction
        });
        
        
        output.inventory_movements_product = await products.getInventory_movements_product({
            transaction
        });
        
        
        
        
        output.order_items_product = await products.getOrder_items_product({
            transaction
        });
        
        
        
        
        
        output.commission_rules_product = await products.getCommission_rules_product({
            transaction
        });
        
        
        
        
        
        output.referral_links_product = await products.getReferral_links_product({
            transaction
        });
        
        
        
        
        
        output.ai_insights_related_product = await products.getAi_insights_related_product({
            transaction
        });
        
        
        
        
        output.tenant = await products.getTenant({
            transaction
        });
        
        
        output.product_images = await products.getProduct_images({
            transaction
        });
        
        
        output.organizations = await products.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              tenant_name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.product_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'product_name',
                        filter.product_name,
                    ),
                };
            }
            
            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.brand) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'brand',
                        filter.brand,
                    ),
                };
            }
            
            if (filter.category) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'category',
                        filter.category,
                    ),
                };
            }
            
            if (filter.unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'unit',
                        filter.unit,
                    ),
                };
            }
            
            if (filter.short_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'short_description',
                        filter.short_description,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    distributor_price: {
                    ...where.distributor_price,
                            [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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

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

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

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

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

    
};

