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

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

        const leaderboard_entries = await db.leaderboard_entries.create(
            {
                id: data.id || undefined,
        
        scope: data.scope
        ||
        null
            ,
            
        rank_position: data.rank_position
        ||
        null
            ,
            
        score_value: data.score_value
        ||
        null
            ,
            
        period_start_at: data.period_start_at
        ||
        null
            ,
            
        period_end_at: data.period_end_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await leaderboard_entries.setUser( data.user || null, {
            transaction,
        });
        
        await leaderboard_entries.setEvent( data.event || null, {
            transaction,
        });
        
        await leaderboard_entries.setMode( data.mode || null, {
            transaction,
        });
        

        

        

        return leaderboard_entries;
    }
    

    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 leaderboard_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                scope: item.scope
            ||
            null
            ,
            
                rank_position: item.rank_position
            ||
            null
            ,
            
                score_value: item.score_value
            ||
            null
            ,
            
                period_start_at: item.period_start_at
            ||
            null
            ,
            
                period_end_at: item.period_end_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return leaderboard_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.scope !== undefined) updatePayload.scope = data.scope;
        
        
        if (data.rank_position !== undefined) updatePayload.rank_position = data.rank_position;
        
        
        if (data.score_value !== undefined) updatePayload.score_value = data.score_value;
        
        
        if (data.period_start_at !== undefined) updatePayload.period_start_at = data.period_start_at;
        
        
        if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await leaderboard_entries.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.event !== undefined) {
            await leaderboard_entries.setEvent(
              
              data.event,
              
              { transaction }
            );
        }
        
        if (data.mode !== undefined) {
            await leaderboard_entries.setMode(
              
              data.mode,
              
              { transaction }
            );
        }
        

        
        

        

        return leaderboard_entries;
    }

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

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

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


        return leaderboard_entries;
    }

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

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

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

        await leaderboard_entries.destroy({
            transaction
        });

        return leaderboard_entries;
    }

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

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

        if (!leaderboard_entries) {
            return leaderboard_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await leaderboard_entries.getUser({
            transaction
        });
        
        
        output.event = await leaderboard_entries.getEvent({
            transaction
        });
        
        
        output.mode = await leaderboard_entries.getMode({
            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.events,
        as: 'event',
        
        where: filter.event ? {
          [Op.or]: [
            { id: { [Op.in]: filter.event.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            period_start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    period_end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

