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

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

        const beatmap_sets = await db.beatmap_sets.create(
            {
                id: data.id || undefined,
        
        osu_beatmapset_numeric: data.osu_beatmapset_numeric
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        artist_name: data.artist_name
        ||
        null
            ,
            
        creator_username: data.creator_username
        ||
        null
            ,
            
        creator_user_numeric: data.creator_user_numeric
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        total_playcount: data.total_playcount
        ||
        null
            ,
            
        background_image_url: data.background_image_url
        ||
        null
            ,
            
        cover_image_url: data.cover_image_url
        ||
        null
            ,
            
        ranked_at: data.ranked_at
        ||
        null
            ,
            
        loved_at: data.loved_at
        ||
        null
            ,
            
        last_synced_at: data.last_synced_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return beatmap_sets;
    }
    

    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 beatmap_setsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                osu_beatmapset_numeric: item.osu_beatmapset_numeric
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                artist_name: item.artist_name
            ||
            null
            ,
            
                creator_username: item.creator_username
            ||
            null
            ,
            
                creator_user_numeric: item.creator_user_numeric
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                total_playcount: item.total_playcount
            ||
            null
            ,
            
                background_image_url: item.background_image_url
            ||
            null
            ,
            
                cover_image_url: item.cover_image_url
            ||
            null
            ,
            
                ranked_at: item.ranked_at
            ||
            null
            ,
            
                loved_at: item.loved_at
            ||
            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 beatmap_sets = await db.beatmap_sets.bulkCreate(beatmap_setsData, { transaction });

        // For each item created, replace relation files
        

        return beatmap_sets;
    }

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

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


        

        const updatePayload = {};
        
        if (data.osu_beatmapset_numeric !== undefined) updatePayload.osu_beatmapset_numeric = data.osu_beatmapset_numeric;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.artist_name !== undefined) updatePayload.artist_name = data.artist_name;
        
        
        if (data.creator_username !== undefined) updatePayload.creator_username = data.creator_username;
        
        
        if (data.creator_user_numeric !== undefined) updatePayload.creator_user_numeric = data.creator_user_numeric;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.total_playcount !== undefined) updatePayload.total_playcount = data.total_playcount;
        
        
        if (data.background_image_url !== undefined) updatePayload.background_image_url = data.background_image_url;
        
        
        if (data.cover_image_url !== undefined) updatePayload.cover_image_url = data.cover_image_url;
        
        
        if (data.ranked_at !== undefined) updatePayload.ranked_at = data.ranked_at;
        
        
        if (data.loved_at !== undefined) updatePayload.loved_at = data.loved_at;
        
        
        if (data.last_synced_at !== undefined) updatePayload.last_synced_at = data.last_synced_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return beatmap_sets;
    }

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

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

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


        return beatmap_sets;
    }

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

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

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

        await beatmap_sets.destroy({
            transaction
        });

        return beatmap_sets;
    }

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

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

        if (!beatmap_sets) {
            return beatmap_sets;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.beatmaps_beatmap_set = await beatmap_sets.getBeatmaps_beatmap_set({
            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.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'beatmap_sets',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.artist_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'beatmap_sets',
                        'artist_name',
                        filter.artist_name,
                    ),
                };
            }
            
            if (filter.creator_username) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'beatmap_sets',
                        'creator_username',
                        filter.creator_username,
                    ),
                };
            }
            
            if (filter.background_image_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'beatmap_sets',
                        'background_image_url',
                        filter.background_image_url,
                    ),
                };
            }
            
            if (filter.cover_image_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'beatmap_sets',
                        'cover_image_url',
                        filter.cover_image_url,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    loved_at: {
                    ...where.loved_at,
                            [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.beatmap_sets.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(
                        'beatmap_sets',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

