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

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

        const artist_profiles = await db.artist_profiles.create(
            {
                id: data.id || undefined,
        
        artist_name: data.artist_name
        ||
        null
            ,
            
        profile_type: data.profile_type
        ||
        null
            ,
            
        legal_name: data.legal_name
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        tax_residency: data.tax_residency
        ||
        null
            ,
            
        payout_currency: data.payout_currency
        ||
        null
            ,
            
        bio: data.bio
        ||
        null
            ,
            
        website_url: data.website_url
        ||
        null
            ,
            
        vk_url: data.vk_url
        ||
        null
            ,
            
        youtube_url: data.youtube_url
        ||
        null
            ,
            
        tiktok_url: data.tiktok_url
        ||
        null
            ,
            
        instagram_url: data.instagram_url
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await artist_profiles.setUser( data.user || null, {
            transaction,
        });
        
        await artist_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return artist_profiles;
    }
    

    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 artist_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                artist_name: item.artist_name
            ||
            null
            ,
            
                profile_type: item.profile_type
            ||
            null
            ,
            
                legal_name: item.legal_name
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                tax_residency: item.tax_residency
            ||
            null
            ,
            
                payout_currency: item.payout_currency
            ||
            null
            ,
            
                bio: item.bio
            ||
            null
            ,
            
                website_url: item.website_url
            ||
            null
            ,
            
                vk_url: item.vk_url
            ||
            null
            ,
            
                youtube_url: item.youtube_url
            ||
            null
            ,
            
                tiktok_url: item.tiktok_url
            ||
            null
            ,
            
                instagram_url: item.instagram_url
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return artist_profiles;
    }

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


        

        const updatePayload = {};
        
        if (data.artist_name !== undefined) updatePayload.artist_name = data.artist_name;
        
        
        if (data.profile_type !== undefined) updatePayload.profile_type = data.profile_type;
        
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.tax_residency !== undefined) updatePayload.tax_residency = data.tax_residency;
        
        
        if (data.payout_currency !== undefined) updatePayload.payout_currency = data.payout_currency;
        
        
        if (data.bio !== undefined) updatePayload.bio = data.bio;
        
        
        if (data.website_url !== undefined) updatePayload.website_url = data.website_url;
        
        
        if (data.vk_url !== undefined) updatePayload.vk_url = data.vk_url;
        
        
        if (data.youtube_url !== undefined) updatePayload.youtube_url = data.youtube_url;
        
        
        if (data.tiktok_url !== undefined) updatePayload.tiktok_url = data.tiktok_url;
        
        
        if (data.instagram_url !== undefined) updatePayload.instagram_url = data.instagram_url;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await artist_profiles.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await artist_profiles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return artist_profiles;
    }

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

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

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


        return artist_profiles;
    }

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

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

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

        await artist_profiles.destroy({
            transaction
        });

        return artist_profiles;
    }

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

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

        if (!artist_profiles) {
            return artist_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.releases_artist_profile = await artist_profiles.getReleases_artist_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.pitch_requests_artist_profile = await artist_profiles.getPitch_requests_artist_profile({
            transaction
        });
        
        
        
        output.royalty_reports_artist_profile = await artist_profiles.getRoyalty_reports_artist_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        output.analytics_daily_artist_profile = await artist_profiles.getAnalytics_daily_artist_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await artist_profiles.getUser({
            transaction
        });
        
        
        output.press_photos = await artist_profiles.getPress_photos({
            transaction
        });
        
        
        output.organizations = await artist_profiles.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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.artist_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'artist_name',
                        filter.artist_name,
                    ),
                };
            }
            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.tax_residency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'tax_residency',
                        filter.tax_residency,
                    ),
                };
            }
            
            if (filter.payout_currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'payout_currency',
                        filter.payout_currency,
                    ),
                };
            }
            
            if (filter.bio) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'bio',
                        filter.bio,
                    ),
                };
            }
            
            if (filter.website_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'website_url',
                        filter.website_url,
                    ),
                };
            }
            
            if (filter.vk_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'vk_url',
                        filter.vk_url,
                    ),
                };
            }
            
            if (filter.youtube_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'youtube_url',
                        filter.youtube_url,
                    ),
                };
            }
            
            if (filter.tiktok_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'tiktok_url',
                        filter.tiktok_url,
                    ),
                };
            }
            
            if (filter.instagram_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artist_profiles',
                        'instagram_url',
                        filter.instagram_url,
                    ),
                };
            }
            

            
            

            

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

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


      

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

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

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

    
};

