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

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

        const achievements = await db.achievements.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        target_value: data.target_value
        ||
        null
            ,
            
        reward_yux: data.reward_yux
        ||
        null
            ,
            
        is_repeatable: data.is_repeatable
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await achievements.setReward_title( data.reward_title || null, {
            transaction,
        });
        
        await achievements.setReward_badge( data.reward_badge || null, {
            transaction,
        });
        

        

        

        return achievements;
    }
    

    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 achievementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                target_value: item.target_value
            ||
            null
            ,
            
                reward_yux: item.reward_yux
            ||
            null
            ,
            
                is_repeatable: item.is_repeatable
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return achievements;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.target_value !== undefined) updatePayload.target_value = data.target_value;
        
        
        if (data.reward_yux !== undefined) updatePayload.reward_yux = data.reward_yux;
        
        
        if (data.is_repeatable !== undefined) updatePayload.is_repeatable = data.is_repeatable;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.reward_title !== undefined) {
            await achievements.setReward_title(
              
              data.reward_title,
              
              { transaction }
            );
        }
        
        if (data.reward_badge !== undefined) {
            await achievements.setReward_badge(
              
              data.reward_badge,
              
              { transaction }
            );
        }
        

        
        

        

        return achievements;
    }

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

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

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


        return achievements;
    }

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

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

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

        await achievements.destroy({
            transaction
        });

        return achievements;
    }

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

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

        if (!achievements) {
            return achievements;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user_achievements_achievement = await achievements.getUser_achievements_achievement({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reward_title = await achievements.getReward_title({
            transaction
        });
        
        
        output.reward_badge = await achievements.getReward_badge({
            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.titles,
        as: 'reward_title',
        
        where: filter.reward_title ? {
          [Op.or]: [
            { id: { [Op.in]: filter.reward_title.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.reward_title.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

            
            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_yuxRange) {
                const [start, end] = filter.reward_yuxRange;

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

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

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

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


      

      



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

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

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

    
};

