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

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

        const badge_rules = await db.badge_rules.create(
            {
                id: data.id || undefined,
        
        badge_type: data.badge_type
        ||
        null
            ,
            
        required_evidence_json: data.required_evidence_json
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        tenant_key: data.tenant_key
        ||
        null
            ,
            
        created_at_ts: data.created_at_ts
        ||
        null
            ,
            
        updated_at_ts: data.updated_at_ts
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return badge_rules;
    }
    

    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 badge_rulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                badge_type: item.badge_type
            ||
            null
            ,
            
                required_evidence_json: item.required_evidence_json
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                tenant_key: item.tenant_key
            ||
            null
            ,
            
                created_at_ts: item.created_at_ts
            ||
            null
            ,
            
                updated_at_ts: item.updated_at_ts
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return badge_rules;
    }

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

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


        

        const updatePayload = {};
        
        if (data.badge_type !== undefined) updatePayload.badge_type = data.badge_type;
        
        
        if (data.required_evidence_json !== undefined) updatePayload.required_evidence_json = data.required_evidence_json;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.tenant_key !== undefined) updatePayload.tenant_key = data.tenant_key;
        
        
        if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
        
        
        if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return badge_rules;
    }

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

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

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


        return badge_rules;
    }

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

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

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

        await badge_rules.destroy({
            transaction
        });

        return badge_rules;
    }

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

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

        if (!badge_rules) {
            return badge_rules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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 = [



    ];

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

            
            if (filter.required_evidence_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'badge_rules',
                        'required_evidence_json',
                        filter.required_evidence_json,
                    ),
                };
            }
            
            if (filter.tenant_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'badge_rules',
                        'tenant_key',
                        filter.tenant_key,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.badge_type) {
                where = {
                    ...where,
                badge_type: filter.badge_type,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_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.badge_rules.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(
                        'badge_rules',
                        'required_evidence_json',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

