
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,
        
        rank: data.rank
        ||
        null
            ,
            
        points: data.points
        ||
        null
            ,
            
        value: data.value
        ||
        null
            ,
            
        recorded_at: data.recorded_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await leaderboard_entries.setLeaderboard( data.leaderboard || null, {
            transaction,
        });
        
        await leaderboard_entries.setUser( data.user || null, {
            transaction,
        });
        
        await leaderboard_entries.setOrganizations( data.organizations || 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,
                
                rank: item.rank
            ||
            null
            ,
            
                points: item.points
            ||
            null
            ,
            
                value: item.value
            ||
            null
            ,
            
                recorded_at: item.recorded_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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.rank !== undefined) updatePayload.rank = data.rank;
        
        
        if (data.points !== undefined) updatePayload.points = data.points;
        
        
        if (data.value !== undefined) updatePayload.value = data.value;
        
        
        if (data.recorded_at !== undefined) updatePayload.recorded_at = data.recorded_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.leaderboard !== undefined) {
            await leaderboard_entries.setLeaderboard(
              
              data.leaderboard,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await leaderboard_entries.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await leaderboard_entries.setOrganizations(
              
              data.organizations,
              
              { 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.leaderboard = await leaderboard_entries.getLeaderboard({
            transaction
        });
        
        
        output.user = await leaderboard_entries.getUser({
            transaction
        });
        
        
        output.organizations = await leaderboard_entries.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        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.organizations,
        as: 'organizations',
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

            


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

