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

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

        const match_players = await db.match_players.create(
            {
                id: data.id || undefined,
        
        display_name: data.display_name
        ||
        null
            ,
            
        player_status: data.player_status
        ||
        null
            ,
            
        score_points: data.score_points
        ||
        null
            ,
            
        correct_count: data.correct_count
        ||
        null
            ,
            
        incorrect_count: data.incorrect_count
        ||
        null
            ,
            
        yux_earned: data.yux_earned
        ||
        null
            ,
            
        race_distance_km: data.race_distance_km
        ||
        null
            ,
            
        joined_at: data.joined_at
        ||
        null
            ,
            
        left_at: data.left_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await match_players.setMatch( data.match || null, {
            transaction,
        });
        
        await match_players.setUser( data.user || null, {
            transaction,
        });
        
        await match_players.setAvatar_customization( data.avatar_customization || null, {
            transaction,
        });
        

        

        

        return match_players;
    }
    

    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 match_playersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                display_name: item.display_name
            ||
            null
            ,
            
                player_status: item.player_status
            ||
            null
            ,
            
                score_points: item.score_points
            ||
            null
            ,
            
                correct_count: item.correct_count
            ||
            null
            ,
            
                incorrect_count: item.incorrect_count
            ||
            null
            ,
            
                yux_earned: item.yux_earned
            ||
            null
            ,
            
                race_distance_km: item.race_distance_km
            ||
            null
            ,
            
                joined_at: item.joined_at
            ||
            null
            ,
            
                left_at: item.left_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return match_players;
    }

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

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


        

        const updatePayload = {};
        
        if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
        
        
        if (data.player_status !== undefined) updatePayload.player_status = data.player_status;
        
        
        if (data.score_points !== undefined) updatePayload.score_points = data.score_points;
        
        
        if (data.correct_count !== undefined) updatePayload.correct_count = data.correct_count;
        
        
        if (data.incorrect_count !== undefined) updatePayload.incorrect_count = data.incorrect_count;
        
        
        if (data.yux_earned !== undefined) updatePayload.yux_earned = data.yux_earned;
        
        
        if (data.race_distance_km !== undefined) updatePayload.race_distance_km = data.race_distance_km;
        
        
        if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
        
        
        if (data.left_at !== undefined) updatePayload.left_at = data.left_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.match !== undefined) {
            await match_players.setMatch(
              
              data.match,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await match_players.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.avatar_customization !== undefined) {
            await match_players.setAvatar_customization(
              
              data.avatar_customization,
              
              { transaction }
            );
        }
        

        
        

        

        return match_players;
    }

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

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

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


        return match_players;
    }

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

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

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

        await match_players.destroy({
            transaction
        });

        return match_players;
    }

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

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

        if (!match_players) {
            return match_players;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.player_answers_match_player = await match_players.getPlayer_answers_match_player({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.match = await match_players.getMatch({
            transaction
        });
        
        
        output.user = await match_players.getUser({
            transaction
        });
        
        
        output.avatar_customization = await match_players.getAvatar_customization({
            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.matches,
        as: 'match',
        
        where: filter.match ? {
          [Op.or]: [
            { id: { [Op.in]: filter.match.split('|').map(term => Utils.uuid(term)) } },
            {
              game_code: {
                [Op.or]: filter.match.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.avatar_customizations,
        as: 'avatar_customization',
        
        where: filter.avatar_customization ? {
          [Op.or]: [
            { id: { [Op.in]: filter.avatar_customization.split('|').map(term => Utils.uuid(term)) } },
            {
              profile_name: {
                [Op.or]: filter.avatar_customization.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

