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

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

        const storage_objects = await db.storage_objects.create(
            {
                id: data.id || undefined,
        
        object_key: data.object_key
        ||
        null
            ,
            
        content_type: data.content_type
        ||
        null
            ,
            
        size_bytes: data.size_bytes
        ||
        null
            ,
            
        etag: data.etag
        ||
        null
            ,
            
        sha256: data.sha256
        ||
        null
            ,
            
        compression_ratio: data.compression_ratio
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        trashed_at: data.trashed_at
        ||
        null
            ,
            
        purge_after: data.purge_after
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await storage_objects.setBucket( data.bucket || null, {
            transaction,
        });
        
        await storage_objects.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.storage_objects.getTableName(),
                belongsToColumn: 'thumbnail_image',
                belongsToId: storage_objects.id,
            },
            data.thumbnail_image,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.storage_objects.getTableName(),
                belongsToColumn: 'preview_file',
                belongsToId: storage_objects.id,
            },
            data.preview_file,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.storage_objects.getTableName(),
                belongsToColumn: 'original_file',
                belongsToId: storage_objects.id,
            },
            data.original_file,
            options,
        );
        

        return storage_objects;
    }
    

    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 storage_objectsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                object_key: item.object_key
            ||
            null
            ,
            
                content_type: item.content_type
            ||
            null
            ,
            
                size_bytes: item.size_bytes
            ||
            null
            ,
            
                etag: item.etag
            ||
            null
            ,
            
                sha256: item.sha256
            ||
            null
            ,
            
                compression_ratio: item.compression_ratio
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                trashed_at: item.trashed_at
            ||
            null
            ,
            
                purge_after: item.purge_after
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return storage_objects;
    }

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


        

        const updatePayload = {};
        
        if (data.object_key !== undefined) updatePayload.object_key = data.object_key;
        
        
        if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
        
        
        if (data.size_bytes !== undefined) updatePayload.size_bytes = data.size_bytes;
        
        
        if (data.etag !== undefined) updatePayload.etag = data.etag;
        
        
        if (data.sha256 !== undefined) updatePayload.sha256 = data.sha256;
        
        
        if (data.compression_ratio !== undefined) updatePayload.compression_ratio = data.compression_ratio;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.trashed_at !== undefined) updatePayload.trashed_at = data.trashed_at;
        
        
        if (data.purge_after !== undefined) updatePayload.purge_after = data.purge_after;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.storage_objects.getTableName(),
                belongsToColumn: 'thumbnail_image',
                belongsToId: storage_objects.id,
            },
            data.thumbnail_image,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.storage_objects.getTableName(),
                belongsToColumn: 'preview_file',
                belongsToId: storage_objects.id,
            },
            data.preview_file,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.storage_objects.getTableName(),
                belongsToColumn: 'original_file',
                belongsToId: storage_objects.id,
            },
            data.original_file,
            options,
        );
        

        return storage_objects;
    }

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

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

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


        return storage_objects;
    }

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

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

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

        await storage_objects.destroy({
            transaction
        });

        return storage_objects;
    }

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

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

        if (!storage_objects) {
            return storage_objects;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.media_items_storage_object = await storage_objects.getMedia_items_storage_object({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.bucket = await storage_objects.getBucket({
            transaction
        });
        
        
        output.thumbnail_image = await storage_objects.getThumbnail_image({
            transaction
        });
        
        
        output.preview_file = await storage_objects.getPreview_file({
            transaction
        });
        
        
        output.original_file = await storage_objects.getOriginal_file({
            transaction
        });
        
        
        output.organizations = await storage_objects.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.storage_buckets,
        as: 'bucket',
        
        where: filter.bucket ? {
          [Op.or]: [
            { id: { [Op.in]: filter.bucket.split('|').map(term => Utils.uuid(term)) } },
            {
              bucket_name: {
                [Op.or]: filter.bucket.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

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

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

    ];

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

            
            if (filter.object_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'storage_objects',
                        'object_key',
                        filter.object_key,
                    ),
                };
            }
            
            if (filter.content_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'storage_objects',
                        'content_type',
                        filter.content_type,
                    ),
                };
            }
            
            if (filter.etag) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'storage_objects',
                        'etag',
                        filter.etag,
                    ),
                };
            }
            
            if (filter.sha256) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'storage_objects',
                        'sha256',
                        filter.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.compression_ratioRange) {
                const [start, end] = filter.compression_ratioRange;

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    purge_after: {
                    ...where.purge_after,
                            [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.storage_objects.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(
                        'storage_objects',
                        'object_key',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

