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

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

        const refresh_tokens = await db.refresh_tokens.create(
            {
                id: data.id || undefined,
        
        token_hash: data.token_hash
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        revoked_at: data.revoked_at
        ||
        null
            ,
            
        ip_address: data.ip_address
        ||
        null
            ,
            
        user_agent: data.user_agent
        ||
        null
            ,
            
        created_at_ts: data.created_at_ts
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await refresh_tokens.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return refresh_tokens;
    }
    

    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 refresh_tokensData = data.map((item, index) => ({
                id: item.id || undefined,
                
                token_hash: item.token_hash
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                revoked_at: item.revoked_at
            ||
            null
            ,
            
                ip_address: item.ip_address
            ||
            null
            ,
            
                user_agent: item.user_agent
            ||
            null
            ,
            
                created_at_ts: item.created_at_ts
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return refresh_tokens;
    }

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

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


        

        const updatePayload = {};
        
        if (data.token_hash !== undefined) updatePayload.token_hash = data.token_hash;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.revoked_at !== undefined) updatePayload.revoked_at = data.revoked_at;
        
        
        if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
        
        
        if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
        
        
        if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await refresh_tokens.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return refresh_tokens;
    }

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

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

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


        return refresh_tokens;
    }

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

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

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

        await refresh_tokens.destroy({
            transaction
        });

        return refresh_tokens;
    }

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

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

        if (!refresh_tokens) {
            return refresh_tokens;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await refresh_tokens.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.token_hash) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'refresh_tokens',
                        'token_hash',
                        filter.token_hash,
                    ),
                };
            }
            
            if (filter.ip_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'refresh_tokens',
                        'ip_address',
                        filter.ip_address,
                    ),
                };
            }
            
            if (filter.user_agent) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'refresh_tokens',
                        'user_agent',
                        filter.user_agent,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    revoked_at: {
                    ...where.revoked_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            


      



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

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

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

    
};

