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

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

        const admin_users = await db.admin_users.create(
            {
                id: data.id || undefined,
        
        email: data.email
        ||
        null
            ,
            
        display_name: data.display_name
        ||
        null
            ,
            
        role: data.role
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        last_login_at: data.last_login_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return admin_users;
    }
    

    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 admin_usersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                email: item.email
            ||
            null
            ,
            
                display_name: item.display_name
            ||
            null
            ,
            
                role: item.role
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                last_login_at: item.last_login_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return admin_users;
    }

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

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


        

        const updatePayload = {};
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
        
        
        if (data.role !== undefined) updatePayload.role = data.role;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.last_login_at !== undefined) updatePayload.last_login_at = data.last_login_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return admin_users;
    }

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

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

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


        return admin_users;
    }

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

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

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

        await admin_users.destroy({
            transaction
        });

        return admin_users;
    }

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

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

        if (!admin_users) {
            return admin_users;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reports_assigned_moderator = await admin_users.getReports_assigned_moderator({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.content_moderation_items_reviewed_by = await admin_users.getContent_moderation_items_reviewed_by({
            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 = [



    ];

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

            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admin_users',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.display_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admin_users',
                        'display_name',
                        filter.display_name,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.role) {
                where = {
                    ...where,
                role: filter.role,
            };
            }
            
            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.admin_users.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(
                        'admin_users',
                        'display_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

