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

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

        const inventory_items = await db.inventory_items.create(
            {
                id: data.id || undefined,
        
        item_kind: data.item_kind
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        unlocked_at: data.unlocked_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inventory_items.setUser( data.user || null, {
            transaction,
        });
        
        await inventory_items.setAvatar( data.avatar || null, {
            transaction,
        });
        
        await inventory_items.setCosmetic( data.cosmetic || null, {
            transaction,
        });
        
        await inventory_items.setTitle_item( data.title_item || null, {
            transaction,
        });
        
        await inventory_items.setBadge( data.badge || null, {
            transaction,
        });
        

        

        

        return inventory_items;
    }
    

    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 inventory_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                item_kind: item.item_kind
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                unlocked_at: item.unlocked_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return inventory_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.item_kind !== undefined) updatePayload.item_kind = data.item_kind;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.unlocked_at !== undefined) updatePayload.unlocked_at = data.unlocked_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await inventory_items.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.avatar !== undefined) {
            await inventory_items.setAvatar(
              
              data.avatar,
              
              { transaction }
            );
        }
        
        if (data.cosmetic !== undefined) {
            await inventory_items.setCosmetic(
              
              data.cosmetic,
              
              { transaction }
            );
        }
        
        if (data.title_item !== undefined) {
            await inventory_items.setTitle_item(
              
              data.title_item,
              
              { transaction }
            );
        }
        
        if (data.badge !== undefined) {
            await inventory_items.setBadge(
              
              data.badge,
              
              { transaction }
            );
        }
        

        
        

        

        return inventory_items;
    }

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

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

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


        return inventory_items;
    }

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

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

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

        await inventory_items.destroy({
            transaction
        });

        return inventory_items;
    }

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

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

        if (!inventory_items) {
            return inventory_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await inventory_items.getUser({
            transaction
        });
        
        
        output.avatar = await inventory_items.getAvatar({
            transaction
        });
        
        
        output.cosmetic = await inventory_items.getCosmetic({
            transaction
        });
        
        
        output.title_item = await inventory_items.getTitle_item({
            transaction
        });
        
        
        output.badge = await inventory_items.getBadge({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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



    ];

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

            

            
            

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

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

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

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

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

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

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


      

      

      

      

      



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

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

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

    
};

