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

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

        const chat_rooms = await db.chat_rooms.create(
            {
                id: data.id || undefined,
        
        room_type: data.room_type
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        private_room: data.private_room
        ||
        false
        
            ,
            
        created_at_time: data.created_at_time
        ||
        null
            ,
            
        last_message_at: data.last_message_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await chat_rooms.setCreated_by_user( data.created_by_user || null, {
            transaction,
        });
        

        

        

        return chat_rooms;
    }
    

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

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

        // For each item created, replace relation files
        

        return chat_rooms;
    }

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

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


        

        const updatePayload = {};
        
        if (data.room_type !== undefined) updatePayload.room_type = data.room_type;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.private_room !== undefined) updatePayload.private_room = data.private_room;
        
        
        if (data.created_at_time !== undefined) updatePayload.created_at_time = data.created_at_time;
        
        
        if (data.last_message_at !== undefined) updatePayload.last_message_at = data.last_message_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.created_by_user !== undefined) {
            await chat_rooms.setCreated_by_user(
              
              data.created_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return chat_rooms;
    }

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

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

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


        return chat_rooms;
    }

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

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

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

        await chat_rooms.destroy({
            transaction
        });

        return chat_rooms;
    }

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

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

        if (!chat_rooms) {
            return chat_rooms;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.chat_memberships_chat_room = await chat_rooms.getChat_memberships_chat_room({
            transaction
        });
        
        
        output.chat_messages_chat_room = await chat_rooms.getChat_messages_chat_room({
            transaction
        });
        
        
        
        
        
        output.created_by_user = await chat_rooms.getCreated_by_user({
            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: 'created_by_user',
        
        where: filter.created_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.created_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'chat_rooms',
                        'name',
                        filter.name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      



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

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

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

    
};

