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

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

        const follows = await db.follows.create(
            {
                id: data.id || undefined,
        
        followed_at: data.followed_at
        ||
        null
            ,
            
        notifications_enabled: data.notifications_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await follows.setFollower_user( data.follower_user || null, {
            transaction,
        });
        
        await follows.setFollowed_creator( data.followed_creator || null, {
            transaction,
        });
        
        await follows.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return follows;
    }
    

    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 followsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                followed_at: item.followed_at
            ||
            null
            ,
            
                notifications_enabled: item.notifications_enabled
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return follows;
    }

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


        

        const updatePayload = {};
        
        if (data.followed_at !== undefined) updatePayload.followed_at = data.followed_at;
        
        
        if (data.notifications_enabled !== undefined) updatePayload.notifications_enabled = data.notifications_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.follower_user !== undefined) {
            await follows.setFollower_user(
              
              data.follower_user,
              
              { transaction }
            );
        }
        
        if (data.followed_creator !== undefined) {
            await follows.setFollowed_creator(
              
              data.followed_creator,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await follows.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return follows;
    }

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

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

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


        return follows;
    }

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

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

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

        await follows.destroy({
            transaction
        });

        return follows;
    }

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

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

        if (!follows) {
            return follows;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.follower_user = await follows.getFollower_user({
            transaction
        });
        
        
        output.followed_creator = await follows.getFollowed_creator({
            transaction
        });
        
        
        output.organizations = await follows.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: 'follower_user',
        
        where: filter.follower_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.follower_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.follower_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.creator_profiles,
        as: 'followed_creator',
        
        where: filter.followed_creator ? {
          [Op.or]: [
            { id: { [Op.in]: filter.followed_creator.split('|').map(term => Utils.uuid(term)) } },
            {
              handle: {
                [Op.or]: filter.followed_creator.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.followed_atRange) {
                const [start, end] = filter.followed_atRange;

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

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

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

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


      

      

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

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

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

    
};

