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

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

        const creator_profiles = await db.creator_profiles.create(
            {
                id: data.id || undefined,
        
        handle: data.handle
        ||
        null
            ,
            
        creator_type: data.creator_type
        ||
        null
            ,
            
        is_verified: data.is_verified
        ||
        false
        
            ,
            
        is_adult_creator: data.is_adult_creator
        ||
        false
        
            ,
            
        slogan: data.slogan
        ||
        null
            ,
            
        about: data.about
        ||
        null
            ,
            
        business_email: data.business_email
        ||
        null
            ,
            
        support_email: data.support_email
        ||
        null
            ,
            
        preferred_language: data.preferred_language
        ||
        null
            ,
            
        category_tags: data.category_tags
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await creator_profiles.setUser( data.user || null, {
            transaction,
        });
        
        await creator_profiles.setProfile_style( data.profile_style || null, {
            transaction,
        });
        
        await creator_profiles.setTip_page( data.tip_page || null, {
            transaction,
        });
        
        await creator_profiles.setMerch_store( data.merch_store || null, {
            transaction,
        });
        
        await creator_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return creator_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 creator_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                handle: item.handle
            ||
            null
            ,
            
                creator_type: item.creator_type
            ||
            null
            ,
            
                is_verified: item.is_verified
            ||
            false
        
            ,
            
                is_adult_creator: item.is_adult_creator
            ||
            false
        
            ,
            
                slogan: item.slogan
            ||
            null
            ,
            
                about: item.about
            ||
            null
            ,
            
                business_email: item.business_email
            ||
            null
            ,
            
                support_email: item.support_email
            ||
            null
            ,
            
                preferred_language: item.preferred_language
            ||
            null
            ,
            
                category_tags: item.category_tags
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.handle !== undefined) updatePayload.handle = data.handle;
        
        
        if (data.creator_type !== undefined) updatePayload.creator_type = data.creator_type;
        
        
        if (data.is_verified !== undefined) updatePayload.is_verified = data.is_verified;
        
        
        if (data.is_adult_creator !== undefined) updatePayload.is_adult_creator = data.is_adult_creator;
        
        
        if (data.slogan !== undefined) updatePayload.slogan = data.slogan;
        
        
        if (data.about !== undefined) updatePayload.about = data.about;
        
        
        if (data.business_email !== undefined) updatePayload.business_email = data.business_email;
        
        
        if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
        
        
        if (data.preferred_language !== undefined) updatePayload.preferred_language = data.preferred_language;
        
        
        if (data.category_tags !== undefined) updatePayload.category_tags = data.category_tags;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await creator_profiles.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.profile_style !== undefined) {
            await creator_profiles.setProfile_style(
              
              data.profile_style,
              
              { transaction }
            );
        }
        
        if (data.tip_page !== undefined) {
            await creator_profiles.setTip_page(
              
              data.tip_page,
              
              { transaction }
            );
        }
        
        if (data.merch_store !== undefined) {
            await creator_profiles.setMerch_store(
              
              data.merch_store,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await creator_profiles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return creator_profiles;
    }

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

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

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


        return creator_profiles;
    }

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

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

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

        await creator_profiles.destroy({
            transaction
        });

        return creator_profiles;
    }

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

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

        if (!creator_profiles) {
            return creator_profiles;
        }

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

        
        
        
        
        
        
        
        output.follows_followed_creator = await creator_profiles.getFollows_followed_creator({
            transaction
        });
        
        
        
        
        output.discovery_items_creator = await creator_profiles.getDiscovery_items_creator({
            transaction
        });
        
        
        output.streams_creator = await creator_profiles.getStreams_creator({
            transaction
        });
        
        
        output.videos_creator = await creator_profiles.getVideos_creator({
            transaction
        });
        
        
        
        
        
        output.tip_pages_creator = await creator_profiles.getTip_pages_creator({
            transaction
        });
        
        
        
        
        output.alerts_creator = await creator_profiles.getAlerts_creator({
            transaction
        });
        
        
        output.overlay_profiles_creator = await creator_profiles.getOverlay_profiles_creator({
            transaction
        });
        
        
        
        
        output.merch_stores_creator = await creator_profiles.getMerch_stores_creator({
            transaction
        });
        
        
        
        
        
        
        
        output.private_mailboxes_owner_creator = await creator_profiles.getPrivate_mailboxes_owner_creator({
            transaction
        });
        
        
        
        
        
        
        
        output.user = await creator_profiles.getUser({
            transaction
        });
        
        
        output.profile_style = await creator_profiles.getProfile_style({
            transaction
        });
        
        
        output.tip_page = await creator_profiles.getTip_page({
            transaction
        });
        
        
        output.merch_store = await creator_profiles.getMerch_store({
            transaction
        });
        
        
        output.organizations = await creator_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.profile_styles,
        as: 'profile_style',
        
        where: filter.profile_style ? {
          [Op.or]: [
            { id: { [Op.in]: filter.profile_style.split('|').map(term => Utils.uuid(term)) } },
            {
              style_name: {
                [Op.or]: filter.profile_style.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.merch_stores,
        as: 'merch_store',
        
        where: filter.merch_store ? {
          [Op.or]: [
            { id: { [Op.in]: filter.merch_store.split('|').map(term => Utils.uuid(term)) } },
            {
              store_name: {
                [Op.or]: filter.merch_store.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.handle) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'creator_profiles',
                        'handle',
                        filter.handle,
                    ),
                };
            }
            
            if (filter.slogan) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'creator_profiles',
                        'slogan',
                        filter.slogan,
                    ),
                };
            }
            
            if (filter.about) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'creator_profiles',
                        'about',
                        filter.about,
                    ),
                };
            }
            
            if (filter.business_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'creator_profiles',
                        'business_email',
                        filter.business_email,
                    ),
                };
            }
            
            if (filter.support_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'creator_profiles',
                        'support_email',
                        filter.support_email,
                    ),
                };
            }
            
            if (filter.preferred_language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'creator_profiles',
                        'preferred_language',
                        filter.preferred_language,
                    ),
                };
            }
            
            if (filter.category_tags) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'creator_profiles',
                        'category_tags',
                        filter.category_tags,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.creator_type) {
                where = {
                    ...where,
                creator_type: filter.creator_type,
            };
            }
            
            if (filter.is_verified) {
                where = {
                    ...where,
                is_verified: filter.is_verified,
            };
            }
            
            if (filter.is_adult_creator) {
                where = {
                    ...where,
                is_adult_creator: filter.is_adult_creator,
            };
            }
            


      

      

      

      

      
      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.creator_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(
                        'creator_profiles',
                        'handle',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

