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

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

        const music_playlists = await db.music_playlists.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        playlist_type: data.playlist_type
        ||
        null
            ,
            
        auto_activate: data.auto_activate
        ||
        false
        
            ,
            
        active_from: data.active_from
        ||
        null
            ,
            
        active_to: data.active_to
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.music_playlists.getTableName(),
                belongsToColumn: 'cover_images',
                belongsToId: music_playlists.id,
            },
            data.cover_images,
            options,
        );
        

        return music_playlists;
    }
    

    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 music_playlistsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                playlist_type: item.playlist_type
            ||
            null
            ,
            
                auto_activate: item.auto_activate
            ||
            false
        
            ,
            
                active_from: item.active_from
            ||
            null
            ,
            
                active_to: item.active_to
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < music_playlists.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.music_playlists.getTableName(),
                    belongsToColumn: 'cover_images',
                    belongsToId: music_playlists[i].id,
                },
                data[i].cover_images,
                options,
            );
        }
        

        return music_playlists;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.playlist_type !== undefined) updatePayload.playlist_type = data.playlist_type;
        
        
        if (data.auto_activate !== undefined) updatePayload.auto_activate = data.auto_activate;
        
        
        if (data.active_from !== undefined) updatePayload.active_from = data.active_from;
        
        
        if (data.active_to !== undefined) updatePayload.active_to = data.active_to;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.music_playlists.getTableName(),
                belongsToColumn: 'cover_images',
                belongsToId: music_playlists.id,
            },
            data.cover_images,
            options,
        );
        

        return music_playlists;
    }

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

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

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


        return music_playlists;
    }

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

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

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

        await music_playlists.destroy({
            transaction
        });

        return music_playlists;
    }

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

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

        if (!music_playlists) {
            return music_playlists;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.music_tracks_playlist = await music_playlists.getMusic_tracks_playlist({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.cover_images = await music_playlists.getCover_images({
            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.file,
        as: 'cover_images',
      },

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'music_playlists',
                        'name',
                        filter.name,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            active_from: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    active_to: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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




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

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

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

    
};

