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

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

        const music_tracks = await db.music_tracks.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        duration_seconds: data.duration_seconds
        ||
        null
            ,
            
        order_index: data.order_index
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await music_tracks.setPlaylist( data.playlist || null, {
            transaction,
        });
        

        

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

        return music_tracks;
    }
    

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

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

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

        return music_tracks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
        
        
        if (data.order_index !== undefined) updatePayload.order_index = data.order_index;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.playlist !== undefined) {
            await music_tracks.setPlaylist(
              
              data.playlist,
              
              { transaction }
            );
        }
        

        
        

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

        return music_tracks;
    }

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

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

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


        return music_tracks;
    }

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

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

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

        await music_tracks.destroy({
            transaction
        });

        return music_tracks;
    }

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

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

        if (!music_tracks) {
            return music_tracks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.playlist = await music_tracks.getPlaylist({
            transaction
        });
        
        
        output.audio_files = await music_tracks.getAudio_files({
            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.music_playlists,
        as: 'playlist',
        
        where: filter.playlist ? {
          [Op.or]: [
            { id: { [Op.in]: filter.playlist.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.playlist.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'audio_files',
      },

    ];

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

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

            
            

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

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

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

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

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

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

            


      



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

        const records = await db.music_tracks.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,
        }));
    }

    
};

