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

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

        const osu_api_credentials = await db.osu_api_credentials.create(
            {
                id: data.id || undefined,
        
        label: data.label
        ||
        null
            ,
            
        osu_client_numeric: data.osu_client_numeric
        ||
        null
            ,
            
        osu_client_secret: data.osu_client_secret
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        last_token_at: data.last_token_at
        ||
        null
            ,
            
        last_used_at: data.last_used_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return osu_api_credentials;
    }
    

    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 osu_api_credentialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                label: item.label
            ||
            null
            ,
            
                osu_client_numeric: item.osu_client_numeric
            ||
            null
            ,
            
                osu_client_secret: item.osu_client_secret
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                last_token_at: item.last_token_at
            ||
            null
            ,
            
                last_used_at: item.last_used_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return osu_api_credentials;
    }

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

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


        

        const updatePayload = {};
        
        if (data.label !== undefined) updatePayload.label = data.label;
        
        
        if (data.osu_client_numeric !== undefined) updatePayload.osu_client_numeric = data.osu_client_numeric;
        
        
        if (data.osu_client_secret !== undefined) updatePayload.osu_client_secret = data.osu_client_secret;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.last_token_at !== undefined) updatePayload.last_token_at = data.last_token_at;
        
        
        if (data.last_used_at !== undefined) updatePayload.last_used_at = data.last_used_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return osu_api_credentials;
    }

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

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

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


        return osu_api_credentials;
    }

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

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

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

        await osu_api_credentials.destroy({
            transaction
        });

        return osu_api_credentials;
    }

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

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

        if (!osu_api_credentials) {
            return osu_api_credentials;
        }

        const output = osu_api_credentials.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.label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'osu_api_credentials',
                        'label',
                        filter.label,
                    ),
                };
            }
            
            if (filter.osu_client_secret) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'osu_api_credentials',
                        'osu_client_secret',
                        filter.osu_client_secret,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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




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

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

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

    
};

