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

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

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

        

        

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

        return achievement_definitions;
    }
    

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

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

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

        return achievement_definitions;
    }

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

        const achievement_definitions = await db.achievement_definitions.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.rarity !== undefined) updatePayload.rarity = data.rarity;
        
        
        if (data.target_value !== undefined) updatePayload.target_value = data.target_value;
        
        
        if (data.metric !== undefined) updatePayload.metric = data.metric;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return achievement_definitions;
    }

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

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

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


        return achievement_definitions;
    }

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

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

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

        await achievement_definitions.destroy({
            transaction
        });

        return achievement_definitions;
    }

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

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

        if (!achievement_definitions) {
            return achievement_definitions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user_achievements_achievement_definition = await achievement_definitions.getUser_achievements_achievement_definition({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.badge_images = await achievement_definitions.getBadge_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.file,
        as: 'badge_images',
      },

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'achievement_definitions',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'achievement_definitions',
                        '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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            if (filter.rarity) {
                where = {
                    ...where,
                rarity: filter.rarity,
            };
            }
            
            if (filter.metric) {
                where = {
                    ...where,
                metric: filter.metric,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            




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

        const records = await db.achievement_definitions.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,
        }));
    }

    
};

