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

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

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

        
        await box_items.setBox( data.box || null, {
            transaction,
        });
        
        await box_items.setAvatar( data.avatar || null, {
            transaction,
        });
        
        await box_items.setCosmetic( data.cosmetic || null, {
            transaction,
        });
        

        

        

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

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

        // For each item created, replace relation files
        

        return box_items;
    }

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

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


        

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

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

        
        
        if (data.box !== undefined) {
            await box_items.setBox(
              
              data.box,
              
              { transaction }
            );
        }
        
        if (data.avatar !== undefined) {
            await box_items.setAvatar(
              
              data.avatar,
              
              { transaction }
            );
        }
        
        if (data.cosmetic !== undefined) {
            await box_items.setCosmetic(
              
              data.cosmetic,
              
              { transaction }
            );
        }
        

        
        

        

        return box_items;
    }

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

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

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


        return box_items;
    }

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

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

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

        await box_items.destroy({
            transaction
        });

        return box_items;
    }

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

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

        if (!box_items) {
            return box_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.box = await box_items.getBox({
            transaction
        });
        
        
        output.avatar = await box_items.getAvatar({
            transaction
        });
        
        
        output.cosmetic = await box_items.getCosmetic({
            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.boxes,
        as: 'box',
        
        where: filter.box ? {
          [Op.or]: [
            { id: { [Op.in]: filter.box.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.box.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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


      

      

      



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

        const records = await db.box_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,
        }));
    }

    
};

