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

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

        const mappers = await db.mappers.create(
            {
                id: data.id || undefined,
        
        osu_user_numeric: data.osu_user_numeric
        ||
        null
            ,
            
        osu_username: data.osu_username
        ||
        null
            ,
            
        avatar_url: data.avatar_url
        ||
        null
            ,
            
        profile_url: data.profile_url
        ||
        null
            ,
            
        banner_url: data.banner_url
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        last_synced_at: data.last_synced_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return mappers;
    }
    

    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 mappersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                osu_user_numeric: item.osu_user_numeric
            ||
            null
            ,
            
                osu_username: item.osu_username
            ||
            null
            ,
            
                avatar_url: item.avatar_url
            ||
            null
            ,
            
                profile_url: item.profile_url
            ||
            null
            ,
            
                banner_url: item.banner_url
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                last_synced_at: item.last_synced_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return mappers;
    }

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

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


        

        const updatePayload = {};
        
        if (data.osu_user_numeric !== undefined) updatePayload.osu_user_numeric = data.osu_user_numeric;
        
        
        if (data.osu_username !== undefined) updatePayload.osu_username = data.osu_username;
        
        
        if (data.avatar_url !== undefined) updatePayload.avatar_url = data.avatar_url;
        
        
        if (data.profile_url !== undefined) updatePayload.profile_url = data.profile_url;
        
        
        if (data.banner_url !== undefined) updatePayload.banner_url = data.banner_url;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.last_synced_at !== undefined) updatePayload.last_synced_at = data.last_synced_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return mappers;
    }

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

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

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


        return mappers;
    }

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

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

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

        await mappers.destroy({
            transaction
        });

        return mappers;
    }

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

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

        if (!mappers) {
            return mappers;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.beatmaps_mapper = await mappers.getBeatmaps_mapper({
            transaction
        });
        
        
        output.mapper_stats_mapper = await mappers.getMapper_stats_mapper({
            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.osu_username) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mappers',
                        'osu_username',
                        filter.osu_username,
                    ),
                };
            }
            
            if (filter.avatar_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mappers',
                        'avatar_url',
                        filter.avatar_url,
                    ),
                };
            }
            
            if (filter.profile_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mappers',
                        'profile_url',
                        filter.profile_url,
                    ),
                };
            }
            
            if (filter.banner_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mappers',
                        'banner_url',
                        filter.banner_url,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    last_synced_at: {
                    ...where.last_synced_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.mappers.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(
                        'mappers',
                        'osu_username',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

