
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,
        
        board_type: data.board_type
        ||
        null
            ,
            
        seed_key: data.seed_key
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        rounds_survived: data.rounds_survived
        ||
        null
            ,
            
        best_streak: data.best_streak
        ||
        null
            ,
            
        achieved_at: data.achieved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await leaderboard_entries.setUser( data.user || null, {
            transaction,
        });
        
        await leaderboard_entries.setSession( data.session || 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,
                
                board_type: item.board_type
            ||
            null
            ,
            
                seed_key: item.seed_key
            ||
            null
            ,
            
                score: item.score
            ||
            null
            ,
            
                rounds_survived: item.rounds_survived
            ||
            null
            ,
            
                best_streak: item.best_streak
            ||
            null
            ,
            
                achieved_at: item.achieved_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.board_type !== undefined) updatePayload.board_type = data.board_type;
        
        
        if (data.seed_key !== undefined) updatePayload.seed_key = data.seed_key;
        
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.rounds_survived !== undefined) updatePayload.rounds_survived = data.rounds_survived;
        
        
        if (data.best_streak !== undefined) updatePayload.best_streak = data.best_streak;
        
        
        if (data.achieved_at !== undefined) updatePayload.achieved_at = data.achieved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await leaderboard_entries.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.session !== undefined) {
            await leaderboard_entries.setSession(
              
              data.session,
              
              { 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.session = await leaderboard_entries.getSession({
            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.game_sessions,
        as: 'session',
        
        where: filter.session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.session.split('|').map(term => Utils.uuid(term)) } },
            {
              session_token: {
                [Op.or]: filter.session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.seed_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'leaderboard_entries',
                        'seed_key',
                        filter.seed_key,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      



            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',
                        'seed_key',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

