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

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

        const file_uploads = await db.file_uploads.create(
            {
                id: data.id || undefined,
        
        original_filename: data.original_filename
        ||
        null
            ,
            
        content_type: data.content_type
        ||
        null
            ,
            
        size_bytes: data.size_bytes
        ||
        null
            ,
            
        checksum_sha256: data.checksum_sha256
        ||
        null
            ,
            
        uploaded_at: data.uploaded_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await file_uploads.setTenant( data.tenant || null, {
            transaction,
        });
        
        await file_uploads.setUploaded_by( data.uploaded_by || null, {
            transaction,
        });
        
        await file_uploads.setSource( data.source || null, {
            transaction,
        });
        
        await file_uploads.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return file_uploads;
    }
    

    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 file_uploadsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                original_filename: item.original_filename
            ||
            null
            ,
            
                content_type: item.content_type
            ||
            null
            ,
            
                size_bytes: item.size_bytes
            ||
            null
            ,
            
                checksum_sha256: item.checksum_sha256
            ||
            null
            ,
            
                uploaded_at: item.uploaded_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return file_uploads;
    }

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


        

        const updatePayload = {};
        
        if (data.original_filename !== undefined) updatePayload.original_filename = data.original_filename;
        
        
        if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
        
        
        if (data.size_bytes !== undefined) updatePayload.size_bytes = data.size_bytes;
        
        
        if (data.checksum_sha256 !== undefined) updatePayload.checksum_sha256 = data.checksum_sha256;
        
        
        if (data.uploaded_at !== undefined) updatePayload.uploaded_at = data.uploaded_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await file_uploads.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.uploaded_by !== undefined) {
            await file_uploads.setUploaded_by(
              
              data.uploaded_by,
              
              { transaction }
            );
        }
        
        if (data.source !== undefined) {
            await file_uploads.setSource(
              
              data.source,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await file_uploads.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return file_uploads;
    }

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

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

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


        return file_uploads;
    }

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

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

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

        await file_uploads.destroy({
            transaction
        });

        return file_uploads;
    }

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

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

        if (!file_uploads) {
            return file_uploads;
        }

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

        
        
        
        
        
        
        
        
        
        output.import_jobs_file_upload = await file_uploads.getImport_jobs_file_upload({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await file_uploads.getTenant({
            transaction
        });
        
        
        output.uploaded_by = await file_uploads.getUploaded_by({
            transaction
        });
        
        
        output.source = await file_uploads.getSource({
            transaction
        });
        
        
        output.file = await file_uploads.getFile({
            transaction
        });
        
        
        output.organizations = await file_uploads.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.original_filename) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'file_uploads',
                        'original_filename',
                        filter.original_filename,
                    ),
                };
            }
            
            if (filter.content_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'file_uploads',
                        'content_type',
                        filter.content_type,
                    ),
                };
            }
            
            if (filter.checksum_sha256) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'file_uploads',
                        'checksum_sha256',
                        filter.checksum_sha256,
                    ),
                };
            }
            

            
            

            
            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.uploaded_atRange) {
                const [start, end] = filter.uploaded_atRange;

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

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

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

            


      

      

      

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

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

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

    
};

