
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Product_variantsDBApi {
    

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

        const product_variants = await db.product_variants.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        sku: data.sku
        ||
        null
            ,
            
        price_iqd: data.price_iqd
        ||
        null
            ,
            
        stock_on_hand: data.stock_on_hand
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        attributes_json: data.attributes_json
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await product_variants.setProduct( data.product || null, {
            transaction,
        });
        

        

        

        return product_variants;
    }
    

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

        // Prepare data - wrapping individual data transformations in a map() method
        const product_variantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                sku: item.sku
            ||
            null
            ,
            
                price_iqd: item.price_iqd
            ||
            null
            ,
            
                stock_on_hand: item.stock_on_hand
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                attributes_json: item.attributes_json
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return product_variants;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.sku !== undefined) updatePayload.sku = data.sku;
        
        
        if (data.price_iqd !== undefined) updatePayload.price_iqd = data.price_iqd;
        
        
        if (data.stock_on_hand !== undefined) updatePayload.stock_on_hand = data.stock_on_hand;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.attributes_json !== undefined) updatePayload.attributes_json = data.attributes_json;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.product !== undefined) {
            await product_variants.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        

        
        

        

        return product_variants;
    }

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

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

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


        return product_variants;
    }

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

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

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

        await product_variants.destroy({
            transaction
        });

        return product_variants;
    }

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

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

        if (!product_variants) {
            return product_variants;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cart_items_variant = await product_variants.getCart_items_variant({
            transaction
        });
        
        
        
        output.order_items_variant = await product_variants.getOrder_items_variant({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.product = await product_variants.getProduct({
            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.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              name_ar: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

            
            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.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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      



            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.product_variants.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

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

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

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

    
};

