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

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

        const challenges = await db.challenges.create(
            {
                id: data.id || undefined,
        
        challenge_name: data.challenge_name
        ||
        null
            ,
            
        challenge_type: data.challenge_type
        ||
        null
            ,
            
        metric_type: data.metric_type
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        target_value: data.target_value
        ||
        null
            ,
            
        reward_points: data.reward_points
        ||
        null
            ,
            
        reward_coins: data.reward_coins
        ||
        null
            ,
            
        starts_at: data.starts_at
        ||
        null
            ,
            
        ends_at: data.ends_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await challenges.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await challenges.setCreated_by( data.created_by || null, {
            transaction,
        });
        

        

        

        return challenges;
    }
    

    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 challengesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                challenge_name: item.challenge_name
            ||
            null
            ,
            
                challenge_type: item.challenge_type
            ||
            null
            ,
            
                metric_type: item.metric_type
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                target_value: item.target_value
            ||
            null
            ,
            
                reward_points: item.reward_points
            ||
            null
            ,
            
                reward_coins: item.reward_coins
            ||
            null
            ,
            
                starts_at: item.starts_at
            ||
            null
            ,
            
                ends_at: item.ends_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return challenges;
    }

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


        

        const updatePayload = {};
        
        if (data.challenge_name !== undefined) updatePayload.challenge_name = data.challenge_name;
        
        
        if (data.challenge_type !== undefined) updatePayload.challenge_type = data.challenge_type;
        
        
        if (data.metric_type !== undefined) updatePayload.metric_type = data.metric_type;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.target_value !== undefined) updatePayload.target_value = data.target_value;
        
        
        if (data.reward_points !== undefined) updatePayload.reward_points = data.reward_points;
        
        
        if (data.reward_coins !== undefined) updatePayload.reward_coins = data.reward_coins;
        
        
        if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
        
        
        if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await challenges.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.created_by !== undefined) {
            await challenges.setCreated_by(
              
              data.created_by,
              
              { transaction }
            );
        }
        

        
        

        

        return challenges;
    }

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

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

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


        return challenges;
    }

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

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

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

        await challenges.destroy({
            transaction
        });

        return challenges;
    }

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

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

        if (!challenges) {
            return challenges;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.challenge_participants_challenge = await challenges.getChallenge_participants_challenge({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await challenges.getOrganization({
            transaction
        });
        
        
        output.created_by = await challenges.getCreated_by({
            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.organizations,
        as: 'organization',
        
      },

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



    ];

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

            
            if (filter.challenge_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'challenges',
                        'challenge_name',
                        filter.challenge_name,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'challenges',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            starts_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    ends_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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


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

        where = {
          ...where,
          organizationId: {[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.challenges.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(
                        'challenges',
                        'challenge_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

