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

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

        const releases = await db.releases.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        release_type: data.release_type
        ||
        null
            ,
            
        language: data.language
        ||
        null
            ,
            
        label_name: data.label_name
        ||
        null
            ,
            
        copyright_notice: data.copyright_notice
        ||
        null
            ,
            
        production_notice: data.production_notice
        ||
        null
            ,
            
        upc_code: data.upc_code
        ||
        null
            ,
            
        upc_source: data.upc_source
        ||
        null
            ,
            
        release_date: data.release_date
        ||
        null
            ,
            
        original_release_date: data.original_release_date
        ||
        null
            ,
            
        moderation_status: data.moderation_status
        ||
        null
            ,
            
        moderation_notes: data.moderation_notes
        ||
        null
            ,
            
        explicit_content: data.explicit_content
        ||
        false
        
            ,
            
        license_accepted: data.license_accepted
        ||
        false
        
            ,
            
        content_id_enabled: data.content_id_enabled
        ||
        false
        
            ,
            
        content_match_enabled: data.content_match_enabled
        ||
        false
        
            ,
            
        internal_catalog_code: data.internal_catalog_code
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await releases.setArtist_profile( data.artist_profile || null, {
            transaction,
        });
        
        await releases.setPrimary_genre( data.primary_genre || null, {
            transaction,
        });
        
        await releases.setSecondary_genre( data.secondary_genre || null, {
            transaction,
        });
        
        await releases.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await releases.setSelected_platforms(data.selected_platforms || [], {
            transaction,
        });
        

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

        return releases;
    }
    

    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 releasesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                release_type: item.release_type
            ||
            null
            ,
            
                language: item.language
            ||
            null
            ,
            
                label_name: item.label_name
            ||
            null
            ,
            
                copyright_notice: item.copyright_notice
            ||
            null
            ,
            
                production_notice: item.production_notice
            ||
            null
            ,
            
                upc_code: item.upc_code
            ||
            null
            ,
            
                upc_source: item.upc_source
            ||
            null
            ,
            
                release_date: item.release_date
            ||
            null
            ,
            
                original_release_date: item.original_release_date
            ||
            null
            ,
            
                moderation_status: item.moderation_status
            ||
            null
            ,
            
                moderation_notes: item.moderation_notes
            ||
            null
            ,
            
                explicit_content: item.explicit_content
            ||
            false
        
            ,
            
                license_accepted: item.license_accepted
            ||
            false
        
            ,
            
                content_id_enabled: item.content_id_enabled
            ||
            false
        
            ,
            
                content_match_enabled: item.content_match_enabled
            ||
            false
        
            ,
            
                internal_catalog_code: item.internal_catalog_code
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return releases;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.release_type !== undefined) updatePayload.release_type = data.release_type;
        
        
        if (data.language !== undefined) updatePayload.language = data.language;
        
        
        if (data.label_name !== undefined) updatePayload.label_name = data.label_name;
        
        
        if (data.copyright_notice !== undefined) updatePayload.copyright_notice = data.copyright_notice;
        
        
        if (data.production_notice !== undefined) updatePayload.production_notice = data.production_notice;
        
        
        if (data.upc_code !== undefined) updatePayload.upc_code = data.upc_code;
        
        
        if (data.upc_source !== undefined) updatePayload.upc_source = data.upc_source;
        
        
        if (data.release_date !== undefined) updatePayload.release_date = data.release_date;
        
        
        if (data.original_release_date !== undefined) updatePayload.original_release_date = data.original_release_date;
        
        
        if (data.moderation_status !== undefined) updatePayload.moderation_status = data.moderation_status;
        
        
        if (data.moderation_notes !== undefined) updatePayload.moderation_notes = data.moderation_notes;
        
        
        if (data.explicit_content !== undefined) updatePayload.explicit_content = data.explicit_content;
        
        
        if (data.license_accepted !== undefined) updatePayload.license_accepted = data.license_accepted;
        
        
        if (data.content_id_enabled !== undefined) updatePayload.content_id_enabled = data.content_id_enabled;
        
        
        if (data.content_match_enabled !== undefined) updatePayload.content_match_enabled = data.content_match_enabled;
        
        
        if (data.internal_catalog_code !== undefined) updatePayload.internal_catalog_code = data.internal_catalog_code;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.artist_profile !== undefined) {
            await releases.setArtist_profile(
              
              data.artist_profile,
              
              { transaction }
            );
        }
        
        if (data.primary_genre !== undefined) {
            await releases.setPrimary_genre(
              
              data.primary_genre,
              
              { transaction }
            );
        }
        
        if (data.secondary_genre !== undefined) {
            await releases.setSecondary_genre(
              
              data.secondary_genre,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await releases.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.selected_platforms !== undefined) {
            await releases.setSelected_platforms(data.selected_platforms, { transaction });
        }
        

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

        return releases;
    }

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

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

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


        return releases;
    }

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

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

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

        await releases.destroy({
            transaction
        });

        return releases;
    }

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

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

        if (!releases) {
            return releases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tracks_release = await releases.getTracks_release({
            transaction
        });
        
        
        
        output.release_deliveries_release = await releases.getRelease_deliveries_release({
            transaction
        });
        
        
        output.smart_links_release = await releases.getSmart_links_release({
            transaction
        });
        
        
        
        
        
        
        
        
        output.royalty_lines_release = await releases.getRoyalty_lines_release({
            transaction
        });
        
        
        
        
        
        
        
        output.analytics_daily_release = await releases.getAnalytics_daily_release({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.artist_profile = await releases.getArtist_profile({
            transaction
        });
        
        
        output.primary_genre = await releases.getPrimary_genre({
            transaction
        });
        
        
        output.secondary_genre = await releases.getSecondary_genre({
            transaction
        });
        
        
        output.cover_art = await releases.getCover_art({
            transaction
        });
        
        
        output.booklet_files = await releases.getBooklet_files({
            transaction
        });
        
        
        output.selected_platforms = await releases.getSelected_platforms({
            transaction
        });
        
        
        output.organizations = await releases.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.artist_profiles,
        as: 'artist_profile',
        
        where: filter.artist_profile ? {
          [Op.or]: [
            { id: { [Op.in]: filter.artist_profile.split('|').map(term => Utils.uuid(term)) } },
            {
              artist_name: {
                [Op.or]: filter.artist_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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


      {
        model: db.distribution_platforms,
        as: 'selected_platforms',
        required: false,
      },


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

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

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'releases',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'releases',
                        'language',
                        filter.language,
                    ),
                };
            }
            
            if (filter.label_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'releases',
                        'label_name',
                        filter.label_name,
                    ),
                };
            }
            
            if (filter.copyright_notice) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'releases',
                        'copyright_notice',
                        filter.copyright_notice,
                    ),
                };
            }
            
            if (filter.production_notice) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'releases',
                        'production_notice',
                        filter.production_notice,
                    ),
                };
            }
            
            if (filter.upc_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'releases',
                        'upc_code',
                        filter.upc_code,
                    ),
                };
            }
            
            if (filter.moderation_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'releases',
                        'moderation_notes',
                        filter.moderation_notes,
                    ),
                };
            }
            
            if (filter.internal_catalog_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'releases',
                        'internal_catalog_code',
                        filter.internal_catalog_code,
                    ),
                };
            }
            

            
            

            
            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.original_release_dateRange) {
                const [start, end] = filter.original_release_dateRange;

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

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

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

            
            if (filter.release_type) {
                where = {
                    ...where,
                release_type: filter.release_type,
            };
            }
            
            if (filter.upc_source) {
                where = {
                    ...where,
                upc_source: filter.upc_source,
            };
            }
            
            if (filter.moderation_status) {
                where = {
                    ...where,
                moderation_status: filter.moderation_status,
            };
            }
            
            if (filter.explicit_content) {
                where = {
                    ...where,
                explicit_content: filter.explicit_content,
            };
            }
            
            if (filter.license_accepted) {
                where = {
                    ...where,
                license_accepted: filter.license_accepted,
            };
            }
            
            if (filter.content_id_enabled) {
                where = {
                    ...where,
                content_id_enabled: filter.content_id_enabled,
            };
            }
            
            if (filter.content_match_enabled) {
                where = {
                    ...where,
                content_match_enabled: filter.content_match_enabled,
            };
            }
            


      

      

      

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

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


      if (filter.selected_platforms) {
        const searchTerms = filter.selected_platforms.split('|');

        include = [
          {
            model: db.distribution_platforms,
            as: 'selected_platforms_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

    
};

