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

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

        const document_versions = await db.document_versions.create(
            {
                id: data.id || undefined,
        
        file_name: data.file_name
        ||
        null
            ,
            
        mime_type: data.mime_type
        ||
        null
            ,
            
        file_size_bytes: data.file_size_bytes
        ||
        null
            ,
            
        change_notes: data.change_notes
        ||
        null
            ,
            
        uploaded_at: data.uploaded_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await document_versions.setDocument( data.document || null, {
            transaction,
        });
        
        await document_versions.setUploaded_by( data.uploaded_by || null, {
            transaction,
        });
        
        await document_versions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return document_versions;
    }
    

    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 document_versionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                file_name: item.file_name
            ||
            null
            ,
            
                mime_type: item.mime_type
            ||
            null
            ,
            
                file_size_bytes: item.file_size_bytes
            ||
            null
            ,
            
                change_notes: item.change_notes
            ||
            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 document_versions = await db.document_versions.bulkCreate(document_versionsData, { transaction });

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

        return document_versions;
    }

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


        

        const updatePayload = {};
        
        if (data.file_name !== undefined) updatePayload.file_name = data.file_name;
        
        
        if (data.mime_type !== undefined) updatePayload.mime_type = data.mime_type;
        
        
        if (data.file_size_bytes !== undefined) updatePayload.file_size_bytes = data.file_size_bytes;
        
        
        if (data.change_notes !== undefined) updatePayload.change_notes = data.change_notes;
        
        
        if (data.uploaded_at !== undefined) updatePayload.uploaded_at = data.uploaded_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.document !== undefined) {
            await document_versions.setDocument(
              
              data.document,
              
              { transaction }
            );
        }
        
        if (data.uploaded_by !== undefined) {
            await document_versions.setUploaded_by(
              
              data.uploaded_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await document_versions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return document_versions;
    }

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

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

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


        return document_versions;
    }

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

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

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

        await document_versions.destroy({
            transaction
        });

        return document_versions;
    }

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

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

        if (!document_versions) {
            return document_versions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.document = await document_versions.getDocument({
            transaction
        });
        
        
        output.uploaded_by = await document_versions.getUploaded_by({
            transaction
        });
        
        
        output.file_blob = await document_versions.getFile_blob({
            transaction
        });
        
        
        output.organizations = await document_versions.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.documents,
        as: 'document',
        
        where: filter.document ? {
          [Op.or]: [
            { id: { [Op.in]: filter.document.split('|').map(term => Utils.uuid(term)) } },
            {
              document_title: {
                [Op.or]: filter.document.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.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.file_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'file_name',
                        filter.file_name,
                    ),
                };
            }
            
            if (filter.mime_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'mime_type',
                        filter.mime_type,
                    ),
                };
            }
            
            if (filter.change_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'change_notes',
                        filter.change_notes,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    file_size_bytes: {
                    ...where.file_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.document_versions.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(
                        'document_versions',
                        'file_name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.document_versions.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,
        }));
    }

    
};

