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

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

        const upload_files = await db.upload_files.create(
            {
                id: data.id || undefined,
        
        file_name: data.file_name
        ||
        null
            ,
            
        content_type: data.content_type
        ||
        null
            ,
            
        size_bytes: data.size_bytes
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        progress_percent: data.progress_percent
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await upload_files.setUpload_session( data.upload_session || null, {
            transaction,
        });
        
        await upload_files.setMedia_item( data.media_item || null, {
            transaction,
        });
        
        await upload_files.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return upload_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 upload_filesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                file_name: item.file_name
            ||
            null
            ,
            
                content_type: item.content_type
            ||
            null
            ,
            
                size_bytes: item.size_bytes
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                progress_percent: item.progress_percent
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.file_name !== undefined) updatePayload.file_name = data.file_name;
        
        
        if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
        
        
        if (data.size_bytes !== undefined) updatePayload.size_bytes = data.size_bytes;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.progress_percent !== undefined) updatePayload.progress_percent = data.progress_percent;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.upload_session !== undefined) {
            await upload_files.setUpload_session(
              
              data.upload_session,
              
              { transaction }
            );
        }
        
        if (data.media_item !== undefined) {
            await upload_files.setMedia_item(
              
              data.media_item,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await upload_files.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return upload_files;
    }

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

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

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


        return upload_files;
    }

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

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

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

        await upload_files.destroy({
            transaction
        });

        return upload_files;
    }

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

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

        if (!upload_files) {
            return upload_files;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.upload_session = await upload_files.getUpload_session({
            transaction
        });
        
        
        output.media_item = await upload_files.getMedia_item({
            transaction
        });
        
        
        output.organizations = await upload_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.upload_sessions,
        as: 'upload_session',
        
        where: filter.upload_session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.upload_session.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.upload_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.media_items,
        as: 'media_item',
        
        where: filter.media_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.media_item.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.file_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'upload_files',
                        'file_name',
                        filter.file_name,
                    ),
                };
            }
            
            if (filter.content_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'upload_files',
                        'content_type',
                        filter.content_type,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'upload_files',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

      
      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.upload_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(
                        'upload_files',
                        'file_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

