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

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

        const rank_tiers = await db.rank_tiers.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        min_points: data.min_points
        ||
        null
            ,
            
        max_points: data.max_points
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.rank_tiers.getTableName(),
                belongsToColumn: 'icon_images',
                belongsToId: rank_tiers.id,
            },
            data.icon_images,
            options,
        );
        

        return rank_tiers;
    }
    

    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 rank_tiersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                min_points: item.min_points
            ||
            null
            ,
            
                max_points: item.max_points
            ||
            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 rank_tiers = await db.rank_tiers.bulkCreate(rank_tiersData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < rank_tiers.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.rank_tiers.getTableName(),
                    belongsToColumn: 'icon_images',
                    belongsToId: rank_tiers[i].id,
                },
                data[i].icon_images,
                options,
            );
        }
        

        return rank_tiers;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.min_points !== undefined) updatePayload.min_points = data.min_points;
        
        
        if (data.max_points !== undefined) updatePayload.max_points = data.max_points;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.rank_tiers.getTableName(),
                belongsToColumn: 'icon_images',
                belongsToId: rank_tiers.id,
            },
            data.icon_images,
            options,
        );
        

        return rank_tiers;
    }

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

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

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


        return rank_tiers;
    }

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

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

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

        await rank_tiers.destroy({
            transaction
        });

        return rank_tiers;
    }

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

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

        if (!rank_tiers) {
            return rank_tiers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user_ranks_rank_tier = await rank_tiers.getUser_ranks_rank_tier({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.icon_images = await rank_tiers.getIcon_images({
            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.file,
        as: 'icon_images',
      },

    ];

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

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

            
            

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

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

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

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

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

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

            




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

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

    
};

