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

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

        const conversation_members = await db.conversation_members.create(
            {
                id: data.id || undefined,
        
        member_role: data.member_role
        ||
        null
            ,
            
        member_status: data.member_status
        ||
        null
            ,
            
        joined_at: data.joined_at
        ||
        null
            ,
            
        last_read_at: data.last_read_at
        ||
        null
            ,
            
        is_muted: data.is_muted
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await conversation_members.setConversation( data.conversation || null, {
            transaction,
        });
        
        await conversation_members.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return conversation_members;
    }
    

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

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

        // For each item created, replace relation files
        

        return conversation_members;
    }

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

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


        

        const updatePayload = {};
        
        if (data.member_role !== undefined) updatePayload.member_role = data.member_role;
        
        
        if (data.member_status !== undefined) updatePayload.member_status = data.member_status;
        
        
        if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
        
        
        if (data.last_read_at !== undefined) updatePayload.last_read_at = data.last_read_at;
        
        
        if (data.is_muted !== undefined) updatePayload.is_muted = data.is_muted;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.conversation !== undefined) {
            await conversation_members.setConversation(
              
              data.conversation,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await conversation_members.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return conversation_members;
    }

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

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

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


        return conversation_members;
    }

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

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

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

        await conversation_members.destroy({
            transaction
        });

        return conversation_members;
    }

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

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

        if (!conversation_members) {
            return conversation_members;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.conversation = await conversation_members.getConversation({
            transaction
        });
        
        
        output.user = await conversation_members.getUser({
            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.conversations,
        as: 'conversation',
        
        where: filter.conversation ? {
          [Op.or]: [
            { id: { [Op.in]: filter.conversation.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.conversation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

            
            if (filter.joined_atRange) {
                const [start, end] = filter.joined_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    joined_at: {
                    ...where.joined_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.last_read_atRange) {
                const [start, end] = filter.last_read_atRange;

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

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

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

            
            if (filter.member_role) {
                where = {
                    ...where,
                member_role: filter.member_role,
            };
            }
            
            if (filter.member_status) {
                where = {
                    ...where,
                member_status: filter.member_status,
            };
            }
            
            if (filter.is_muted) {
                where = {
                    ...where,
                is_muted: filter.is_muted,
            };
            }
            


      

      



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

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

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

    
};

