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

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

        const health_vault_documents = await db.health_vault_documents.create(
            {
                id: data.id || undefined,
        
        document_name: data.document_name
        ||
        null
            ,
            
        document_date: data.document_date
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        issuing_institution: data.issuing_institution
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        shared: data.shared
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await health_vault_documents.setUser( data.user || null, {
            transaction,
        });
        

        

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

        return health_vault_documents;
    }
    

    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 health_vault_documentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                document_name: item.document_name
            ||
            null
            ,
            
                document_date: item.document_date
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                issuing_institution: item.issuing_institution
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                shared: item.shared
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return health_vault_documents;
    }

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

        const health_vault_documents = await db.health_vault_documents.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.document_name !== undefined) updatePayload.document_name = data.document_name;
        
        
        if (data.document_date !== undefined) updatePayload.document_date = data.document_date;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.issuing_institution !== undefined) updatePayload.issuing_institution = data.issuing_institution;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.shared !== undefined) updatePayload.shared = data.shared;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await health_vault_documents.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

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

        return health_vault_documents;
    }

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

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

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


        return health_vault_documents;
    }

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

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

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

        await health_vault_documents.destroy({
            transaction
        });

        return health_vault_documents;
    }

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

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

        if (!health_vault_documents) {
            return health_vault_documents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await health_vault_documents.getUser({
            transaction
        });
        
        
        output.encrypted_file_blob = await health_vault_documents.getEncrypted_file_blob({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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



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

    ];

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

            
            if (filter.document_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'health_vault_documents',
                        'document_name',
                        filter.document_name,
                    ),
                };
            }
            
            if (filter.issuing_institution) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'health_vault_documents',
                        'issuing_institution',
                        filter.issuing_institution,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'health_vault_documents',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.health_vault_documents.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'health_vault_documents',
                        'document_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

