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

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

        const song_metadata = await db.song_metadata.create(
            {
                id: data.id || undefined,
        
        isrc: data.isrc
        ||
        null
            ,
            
        upc: data.upc
        ||
        null
            ,
            
        release_title: data.release_title
        ||
        null
            ,
            
        release_date: data.release_date
        ||
        null
            ,
            
        label_name: data.label_name
        ||
        null
            ,
            
        publisher: data.publisher
        ||
        null
            ,
            
        copyright_notice: data.copyright_notice
        ||
        null
            ,
            
        distribution_status: data.distribution_status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await song_metadata.setSong( data.song || null, {
            transaction,
        });
        
        await song_metadata.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return song_metadata;
    }
    

    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 song_metadataData = data.map((item, index) => ({
                id: item.id || undefined,
                
                isrc: item.isrc
            ||
            null
            ,
            
                upc: item.upc
            ||
            null
            ,
            
                release_title: item.release_title
            ||
            null
            ,
            
                release_date: item.release_date
            ||
            null
            ,
            
                label_name: item.label_name
            ||
            null
            ,
            
                publisher: item.publisher
            ||
            null
            ,
            
                copyright_notice: item.copyright_notice
            ||
            null
            ,
            
                distribution_status: item.distribution_status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return song_metadata;
    }

    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 song_metadata = await db.song_metadata.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.isrc !== undefined) updatePayload.isrc = data.isrc;
        
        
        if (data.upc !== undefined) updatePayload.upc = data.upc;
        
        
        if (data.release_title !== undefined) updatePayload.release_title = data.release_title;
        
        
        if (data.release_date !== undefined) updatePayload.release_date = data.release_date;
        
        
        if (data.label_name !== undefined) updatePayload.label_name = data.label_name;
        
        
        if (data.publisher !== undefined) updatePayload.publisher = data.publisher;
        
        
        if (data.copyright_notice !== undefined) updatePayload.copyright_notice = data.copyright_notice;
        
        
        if (data.distribution_status !== undefined) updatePayload.distribution_status = data.distribution_status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.song !== undefined) {
            await song_metadata.setSong(
              
              data.song,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await song_metadata.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return song_metadata;
    }

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

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

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


        return song_metadata;
    }

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

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

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

        await song_metadata.destroy({
            transaction
        });

        return song_metadata;
    }

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

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

        if (!song_metadata) {
            return song_metadata;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.song = await song_metadata.getSong({
            transaction
        });
        
        
        output.organizations = await song_metadata.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.songs,
        as: 'song',
        
        where: filter.song ? {
          [Op.or]: [
            { id: { [Op.in]: filter.song.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.song.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.isrc) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'song_metadata',
                        'isrc',
                        filter.isrc,
                    ),
                };
            }
            
            if (filter.upc) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'song_metadata',
                        'upc',
                        filter.upc,
                    ),
                };
            }
            
            if (filter.release_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'song_metadata',
                        'release_title',
                        filter.release_title,
                    ),
                };
            }
            
            if (filter.label_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'song_metadata',
                        'label_name',
                        filter.label_name,
                    ),
                };
            }
            
            if (filter.publisher) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'song_metadata',
                        'publisher',
                        filter.publisher,
                    ),
                };
            }
            
            if (filter.copyright_notice) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'song_metadata',
                        'copyright_notice',
                        filter.copyright_notice,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

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

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

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

    
};

