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

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

        const songs = await db.songs.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        artist_display: data.artist_display
        ||
        null
            ,
            
        bpm: data.bpm
        ||
        null
            ,
            
        key_signature: data.key_signature
        ||
        null
            ,
            
        mood: data.mood
        ||
        null
            ,
            
        duration_seconds: data.duration_seconds
        ||
        null
            ,
            
        explicit_content: data.explicit_content
        ||
        false
        
            ,
            
        lyrics: data.lyrics
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await songs.setProject( data.project || null, {
            transaction,
        });
        
        await songs.setGenre( data.genre || null, {
            transaction,
        });
        
        await songs.setVocal_language( data.vocal_language || null, {
            transaction,
        });
        
        await songs.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return songs;
    }
    

    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 songsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                artist_display: item.artist_display
            ||
            null
            ,
            
                bpm: item.bpm
            ||
            null
            ,
            
                key_signature: item.key_signature
            ||
            null
            ,
            
                mood: item.mood
            ||
            null
            ,
            
                duration_seconds: item.duration_seconds
            ||
            null
            ,
            
                explicit_content: item.explicit_content
            ||
            false
        
            ,
            
                lyrics: item.lyrics
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return songs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.artist_display !== undefined) updatePayload.artist_display = data.artist_display;
        
        
        if (data.bpm !== undefined) updatePayload.bpm = data.bpm;
        
        
        if (data.key_signature !== undefined) updatePayload.key_signature = data.key_signature;
        
        
        if (data.mood !== undefined) updatePayload.mood = data.mood;
        
        
        if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
        
        
        if (data.explicit_content !== undefined) updatePayload.explicit_content = data.explicit_content;
        
        
        if (data.lyrics !== undefined) updatePayload.lyrics = data.lyrics;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await songs.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.genre !== undefined) {
            await songs.setGenre(
              
              data.genre,
              
              { transaction }
            );
        }
        
        if (data.vocal_language !== undefined) {
            await songs.setVocal_language(
              
              data.vocal_language,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await songs.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return songs;
    }

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

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

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


        return songs;
    }

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

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

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

        await songs.destroy({
            transaction
        });

        return songs;
    }

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

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

        if (!songs) {
            return songs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.song_metadata_song = await songs.getSong_metadata_song({
            transaction
        });
        
        
        output.assets_song = await songs.getAssets_song({
            transaction
        });
        
        
        output.recording_sessions_song = await songs.getRecording_sessions_song({
            transaction
        });
        
        
        output.tracks_song = await songs.getTracks_song({
            transaction
        });
        
        
        output.arrangement_sections_song = await songs.getArrangement_sections_song({
            transaction
        });
        
        
        output.generation_requests_song = await songs.getGeneration_requests_song({
            transaction
        });
        
        
        
        
        output.mix_sessions_song = await songs.getMix_sessions_song({
            transaction
        });
        
        
        output.mastering_sessions_song = await songs.getMastering_sessions_song({
            transaction
        });
        
        
        output.exports_song = await songs.getExports_song({
            transaction
        });
        
        
        output.cover_artworks_song = await songs.getCover_artworks_song({
            transaction
        });
        
        
        
        
        
        output.project = await songs.getProject({
            transaction
        });
        
        
        output.genre = await songs.getGenre({
            transaction
        });
        
        
        output.vocal_language = await songs.getVocal_language({
            transaction
        });
        
        
        output.organizations = await songs.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.genres,
        as: 'genre',
        
        where: filter.genre ? {
          [Op.or]: [
            { id: { [Op.in]: filter.genre.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.genre.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.languages,
        as: 'vocal_language',
        
        where: filter.vocal_language ? {
          [Op.or]: [
            { id: { [Op.in]: filter.vocal_language.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.vocal_language.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'songs',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.artist_display) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'songs',
                        'artist_display',
                        filter.artist_display,
                    ),
                };
            }
            
            if (filter.key_signature) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'songs',
                        'key_signature',
                        filter.key_signature,
                    ),
                };
            }
            
            if (filter.lyrics) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'songs',
                        'lyrics',
                        filter.lyrics,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    bpm: {
                    ...where.bpm,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.songs.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'songs',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

    
};

