
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,
        
        sku: data.sku
        ||
        null
            ,
            
        product_name: data.product_name
        ||
        null
            ,
            
        brand: data.brand
        ||
        null
            ,
            
        short_description: data.short_description
        ||
        null
            ,
            
        long_description: data.long_description
        ||
        null
            ,
            
        pack_size: data.pack_size
        ||
        null
            ,
            
        units_per_case: data.units_per_case
        ||
        null
            ,
            
        unit_weight_lbs: data.unit_weight_lbs
        ||
        null
            ,
            
        case_weight_lbs: data.case_weight_lbs
        ||
        null
            ,
            
        uom: data.uom
        ||
        null
            ,
            
        moq_cases: data.moq_cases
        ||
        null
            ,
            
        temperature_zone: data.temperature_zone
        ||
        null
            ,
            
        product_status: data.product_status
        ||
        null
            ,
            
        allergens: data.allergens
        ||
        null
            ,
            
        certifications: data.certifications
        ||
        null
            ,
            
        is_sample_eligible: data.is_sample_eligible
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'images',
                belongsToId: products.id,
            },
            data.images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'spec_sheet',
                belongsToId: products.id,
            },
            data.spec_sheet,
            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,
                
                sku: item.sku
            ||
            null
            ,
            
                product_name: item.product_name
            ||
            null
            ,
            
                brand: item.brand
            ||
            null
            ,
            
                short_description: item.short_description
            ||
            null
            ,
            
                long_description: item.long_description
            ||
            null
            ,
            
                pack_size: item.pack_size
            ||
            null
            ,
            
                units_per_case: item.units_per_case
            ||
            null
            ,
            
                unit_weight_lbs: item.unit_weight_lbs
            ||
            null
            ,
            
                case_weight_lbs: item.case_weight_lbs
            ||
            null
            ,
            
                uom: item.uom
            ||
            null
            ,
            
                moq_cases: item.moq_cases
            ||
            null
            ,
            
                temperature_zone: item.temperature_zone
            ||
            null
            ,
            
                product_status: item.product_status
            ||
            null
            ,
            
                allergens: item.allergens
            ||
            null
            ,
            
                certifications: item.certifications
            ||
            null
            ,
            
                is_sample_eligible: item.is_sample_eligible
            ||
            false
        
            ,
            
            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,
            );
        }
        
        for (let i = 0; i < products.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.products.getTableName(),
                    belongsToColumn: 'spec_sheet',
                    belongsToId: products[i].id,
                },
                data[i].spec_sheet,
                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.sku !== undefined) updatePayload.sku = data.sku;
        
        
        if (data.product_name !== undefined) updatePayload.product_name = data.product_name;
        
        
        if (data.brand !== undefined) updatePayload.brand = data.brand;
        
        
        if (data.short_description !== undefined) updatePayload.short_description = data.short_description;
        
        
        if (data.long_description !== undefined) updatePayload.long_description = data.long_description;
        
        
        if (data.pack_size !== undefined) updatePayload.pack_size = data.pack_size;
        
        
        if (data.units_per_case !== undefined) updatePayload.units_per_case = data.units_per_case;
        
        
        if (data.unit_weight_lbs !== undefined) updatePayload.unit_weight_lbs = data.unit_weight_lbs;
        
        
        if (data.case_weight_lbs !== undefined) updatePayload.case_weight_lbs = data.case_weight_lbs;
        
        
        if (data.uom !== undefined) updatePayload.uom = data.uom;
        
        
        if (data.moq_cases !== undefined) updatePayload.moq_cases = data.moq_cases;
        
        
        if (data.temperature_zone !== undefined) updatePayload.temperature_zone = data.temperature_zone;
        
        
        if (data.product_status !== undefined) updatePayload.product_status = data.product_status;
        
        
        if (data.allergens !== undefined) updatePayload.allergens = data.allergens;
        
        
        if (data.certifications !== undefined) updatePayload.certifications = data.certifications;
        
        
        if (data.is_sample_eligible !== undefined) updatePayload.is_sample_eligible = data.is_sample_eligible;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'images',
                belongsToId: products.id,
            },
            data.images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.products.getTableName(),
                belongsToColumn: 'spec_sheet',
                belongsToId: products.id,
            },
            data.spec_sheet,
            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.price_list_items_product = await products.getPrice_list_items_product({
            transaction
        });
        
        
        
        
        output.cart_items_product = await products.getCart_items_product({
            transaction
        });
        
        
        
        output.order_items_product = await products.getOrder_items_product({
            transaction
        });
        
        
        
        
        output.quote_items_product = await products.getQuote_items_product({
            transaction
        });
        
        
        output.sample_requests_product = await products.getSample_requests_product({
            transaction
        });
        
        
        
        output.saved_list_items_product = await products.getSaved_list_items_product({
            transaction
        });
        
        
        
        output.category = await products.getCategory({
            transaction
        });
        
        
        output.images = await products.getImages({
            transaction
        });
        
        
        output.spec_sheet = await products.getSpec_sheet({
            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)) } },
            {
              category_name: {
                [Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

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

    ];

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

            
            if (filter.sku) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'sku',
                        filter.sku,
                    ),
                };
            }
            
            if (filter.product_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'product_name',
                        filter.product_name,
                    ),
                };
            }
            
            if (filter.brand) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'brand',
                        filter.brand,
                    ),
                };
            }
            
            if (filter.short_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'short_description',
                        filter.short_description,
                    ),
                };
            }
            
            if (filter.long_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'long_description',
                        filter.long_description,
                    ),
                };
            }
            
            if (filter.pack_size) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'pack_size',
                        filter.pack_size,
                    ),
                };
            }
            
            if (filter.uom) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'uom',
                        filter.uom,
                    ),
                };
            }
            
            if (filter.allergens) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'allergens',
                        filter.allergens,
                    ),
                };
            }
            
            if (filter.certifications) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'products',
                        'certifications',
                        filter.certifications,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      



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

    
};

