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

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

        const player_profiles = await db.player_profiles.create(
            {
                id: data.id || undefined,
        
        gender: data.gender
        ||
        null
            ,
            
        first_name: data.first_name
        ||
        null
            ,
            
        last_name: data.last_name
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        level: data.level
        ||
        null
            ,
            
        experience_points: data.experience_points
        ||
        null
            ,
            
        money_balance: data.money_balance
        ||
        null
            ,
            
        pix_balance: data.pix_balance
        ||
        null
            ,
            
        reputation_score: data.reputation_score
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await player_profiles.setUser( data.user || null, {
            transaction,
        });
        
        await player_profiles.setHome_location( data.home_location || null, {
            transaction,
        });
        

        

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

        return player_profiles;
    }
    

    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 player_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                gender: item.gender
            ||
            null
            ,
            
                first_name: item.first_name
            ||
            null
            ,
            
                last_name: item.last_name
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                level: item.level
            ||
            null
            ,
            
                experience_points: item.experience_points
            ||
            null
            ,
            
                money_balance: item.money_balance
            ||
            null
            ,
            
                pix_balance: item.pix_balance
            ||
            null
            ,
            
                reputation_score: item.reputation_score
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return player_profiles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.gender !== undefined) updatePayload.gender = data.gender;
        
        
        if (data.first_name !== undefined) updatePayload.first_name = data.first_name;
        
        
        if (data.last_name !== undefined) updatePayload.last_name = data.last_name;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.level !== undefined) updatePayload.level = data.level;
        
        
        if (data.experience_points !== undefined) updatePayload.experience_points = data.experience_points;
        
        
        if (data.money_balance !== undefined) updatePayload.money_balance = data.money_balance;
        
        
        if (data.pix_balance !== undefined) updatePayload.pix_balance = data.pix_balance;
        
        
        if (data.reputation_score !== undefined) updatePayload.reputation_score = data.reputation_score;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await player_profiles.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.home_location !== undefined) {
            await player_profiles.setHome_location(
              
              data.home_location,
              
              { transaction }
            );
        }
        

        
        

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

        return player_profiles;
    }

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

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

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


        return player_profiles;
    }

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

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

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

        await player_profiles.destroy({
            transaction
        });

        return player_profiles;
    }

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

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

        if (!player_profiles) {
            return player_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.npc_relationships_player_profile = await player_profiles.getNpc_relationships_player_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.farm_plots_owner_profile = await player_profiles.getFarm_plots_owner_profile({
            transaction
        });
        
        
        
        
        
        output.fishing_catches_player_profile = await player_profiles.getFishing_catches_player_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.user = await player_profiles.getUser({
            transaction
        });
        
        
        output.home_location = await player_profiles.getHome_location({
            transaction
        });
        
        
        output.character_images = await player_profiles.getCharacter_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.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.locations,
        as: 'home_location',
        
        where: filter.home_location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.home_location.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.home_location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'character_images',
      },

    ];

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

            
            if (filter.first_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'player_profiles',
                        'first_name',
                        filter.first_name,
                    ),
                };
            }
            
            if (filter.last_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'player_profiles',
                        'last_name',
                        filter.last_name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      



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

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

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

    
};

