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

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

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

        
        await user_relationships.setFollower( data.follower || null, {
            transaction,
        });
        
        await user_relationships.setFollowing( data.following || null, {
            transaction,
        });
        

        

        

        return user_relationships;
    }
    

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

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

        // For each item created, replace relation files
        

        return user_relationships;
    }

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

        const user_relationships = await db.user_relationships.findByPk(id, {}, {transaction});


        

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

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

        
        
        if (data.follower !== undefined) {
            await user_relationships.setFollower(
              
              data.follower,
              
              { transaction }
            );
        }
        
        if (data.following !== undefined) {
            await user_relationships.setFollowing(
              
              data.following,
              
              { transaction }
            );
        }
        

        
        

        

        return user_relationships;
    }

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

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

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


        return user_relationships;
    }

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

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

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

        await user_relationships.destroy({
            transaction
        });

        return user_relationships;
    }

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

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

        if (!user_relationships) {
            return user_relationships;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.follower = await user_relationships.getFollower({
            transaction
        });
        
        
        output.following = await user_relationships.getFollowing({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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



    ];

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

            

            
            

            

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

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


      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.user_relationships.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'user_relationships',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

