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

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

        const message_attachments = await db.message_attachments.create(
            {
                id: data.id || undefined,
        
        attachment_type: data.attachment_type
        ||
        null
            ,
            
        caption: data.caption
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await message_attachments.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.message_attachments.getTableName(),
                belongsToColumn: 'image_items',
                belongsToId: message_attachments.id,
            },
            data.image_items,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.message_attachments.getTableName(),
                belongsToColumn: 'file_items',
                belongsToId: message_attachments.id,
            },
            data.file_items,
            options,
        );
        

        return message_attachments;
    }
    

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

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

        // For each item created, replace relation files
        
        for (let i = 0; i < message_attachments.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.message_attachments.getTableName(),
                    belongsToColumn: 'image_items',
                    belongsToId: message_attachments[i].id,
                },
                data[i].image_items,
                options,
            );
        }
        
        for (let i = 0; i < message_attachments.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.message_attachments.getTableName(),
                    belongsToColumn: 'file_items',
                    belongsToId: message_attachments[i].id,
                },
                data[i].file_items,
                options,
            );
        }
        

        return message_attachments;
    }

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


        

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

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

        
        
        if (data.organizations !== undefined) {
            await message_attachments.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.message_attachments.getTableName(),
                belongsToColumn: 'image_items',
                belongsToId: message_attachments.id,
            },
            data.image_items,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.message_attachments.getTableName(),
                belongsToColumn: 'file_items',
                belongsToId: message_attachments.id,
            },
            data.file_items,
            options,
        );
        

        return message_attachments;
    }

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

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

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


        return message_attachments;
    }

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

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

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

        await message_attachments.destroy({
            transaction
        });

        return message_attachments;
    }

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

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

        if (!message_attachments) {
            return message_attachments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.image_items = await message_attachments.getImage_items({
            transaction
        });
        
        
        output.file_items = await message_attachments.getFile_items({
            transaction
        });
        
        
        output.organizations = await message_attachments.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.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'image_items',
      },

      {
        model: db.file,
        as: 'file_items',
      },

    ];

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

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

            
            

            

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

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


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

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

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

    
};

