
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,
        
        tokenHash: data.tokenHash
        ||
        null
            ,
            
        expiresAt: data.expiresAt
        ||
        null
            ,
            
        isRevoked: data.isRevoked
        ||
        false
        
            ,
            
        ipAddress: data.ipAddress
        ||
        null
            ,
            
        userAgent: data.userAgent
        ||
        null
            ,
            
        issuedAt: data.issuedAt
        ||
        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,
                
                tokenHash: item.tokenHash
            ||
            null
            ,
            
                expiresAt: item.expiresAt
            ||
            null
            ,
            
                isRevoked: item.isRevoked
            ||
            false
        
            ,
            
                ipAddress: item.ipAddress
            ||
            null
            ,
            
                userAgent: item.userAgent
            ||
            null
            ,
            
                issuedAt: item.issuedAt
            ||
            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.tokenHash !== undefined) updatePayload.tokenHash = data.tokenHash;
        
        
        if (data.expiresAt !== undefined) updatePayload.expiresAt = data.expiresAt;
        
        
        if (data.isRevoked !== undefined) updatePayload.isRevoked = data.isRevoked;
        
        
        if (data.ipAddress !== undefined) updatePayload.ipAddress = data.ipAddress;
        
        
        if (data.userAgent !== undefined) updatePayload.userAgent = data.userAgent;
        
        
        if (data.issuedAt !== undefined) updatePayload.issuedAt = data.issuedAt;
        
        
        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.tokenHash) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'refresh_tokens',
                        'tokenHash',
                        filter.tokenHash,
                    ),
                };
            }
            
            if (filter.ipAddress) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'refresh_tokens',
                        'ipAddress',
                        filter.ipAddress,
                    ),
                };
            }
            
            if (filter.userAgent) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'refresh_tokens',
                        'userAgent',
                        filter.userAgent,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      



            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',
                        'tokenHash',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

