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

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

        const challenge_participants = await db.challenge_participants.create(
            {
                id: data.id || undefined,
        
        participant_type: data.participant_type
        ||
        null
            ,
            
        current_value: data.current_value
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        rank_position: data.rank_position
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await challenge_participants.setChallenge( data.challenge || null, {
            transaction,
        });
        
        await challenge_participants.setUser( data.user || null, {
            transaction,
        });
        
        await challenge_participants.setTeam( data.team || null, {
            transaction,
        });
        
        await challenge_participants.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return challenge_participants;
    }
    

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

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

        // For each item created, replace relation files
        

        return challenge_participants;
    }

    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 challenge_participants = await db.challenge_participants.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.participant_type !== undefined) updatePayload.participant_type = data.participant_type;
        
        
        if (data.current_value !== undefined) updatePayload.current_value = data.current_value;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.rank_position !== undefined) updatePayload.rank_position = data.rank_position;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.challenge !== undefined) {
            await challenge_participants.setChallenge(
              
              data.challenge,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await challenge_participants.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.team !== undefined) {
            await challenge_participants.setTeam(
              
              data.team,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await challenge_participants.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return challenge_participants;
    }

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

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

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


        return challenge_participants;
    }

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

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

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

        await challenge_participants.destroy({
            transaction
        });

        return challenge_participants;
    }

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

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

        if (!challenge_participants) {
            return challenge_participants;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.challenge = await challenge_participants.getChallenge({
            transaction
        });
        
        
        output.user = await challenge_participants.getUser({
            transaction
        });
        
        
        output.team = await challenge_participants.getTeam({
            transaction
        });
        
        
        output.organizations = await challenge_participants.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.challenges,
        as: 'challenge',
        
        where: filter.challenge ? {
          [Op.or]: [
            { id: { [Op.in]: filter.challenge.split('|').map(term => Utils.uuid(term)) } },
            {
              challenge_name: {
                [Op.or]: filter.challenge.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.teams,
        as: 'team',
        
        where: filter.team ? {
          [Op.or]: [
            { id: { [Op.in]: filter.team.split('|').map(term => Utils.uuid(term)) } },
            {
              team_name: {
                [Op.or]: filter.team.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.current_valueRange) {
                const [start, end] = filter.current_valueRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    current_value: {
                    ...where.current_value,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      

      

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

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

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

    
};

