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

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

        const room_files = await db.room_files.create(
            {
                id: data.id || undefined,
        
        visibility: data.visibility
        ||
        null
            ,
            
        added_at: data.added_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await room_files.setRoom( data.room || null, {
            transaction,
        });
        
        await room_files.setFile( data.file || null, {
            transaction,
        });
        
        await room_files.setAdded_by( data.added_by || null, {
            transaction,
        });
        
        await room_files.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return room_files;
    }
    

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

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

        // For each item created, replace relation files
        

        return room_files;
    }

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


        

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

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

        
        
        if (data.room !== undefined) {
            await room_files.setRoom(
              
              data.room,
              
              { transaction }
            );
        }
        
        if (data.file !== undefined) {
            await room_files.setFile(
              
              data.file,
              
              { transaction }
            );
        }
        
        if (data.added_by !== undefined) {
            await room_files.setAdded_by(
              
              data.added_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await room_files.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return room_files;
    }

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

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

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


        return room_files;
    }

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

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

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

        await room_files.destroy({
            transaction
        });

        return room_files;
    }

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

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

        if (!room_files) {
            return room_files;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.room = await room_files.getRoom({
            transaction
        });
        
        
        output.file = await room_files.getFile({
            transaction
        });
        
        
        output.added_by = await room_files.getAdded_by({
            transaction
        });
        
        
        output.organizations = await room_files.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.rooms,
        as: 'room',
        
        where: filter.room ? {
          [Op.or]: [
            { id: { [Op.in]: filter.room.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.room.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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

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


      

      

      

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

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

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

    
};

