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

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

        const lab_documents = await db.lab_documents.create(
            {
                id: data.id || undefined,
        
        document_date: data.document_date
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        reviewed_with_doctor: data.reviewed_with_doctor
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await lab_documents.setUser( data.user || null, {
            transaction,
        });
        
        await lab_documents.setOrdered_by_provider( data.ordered_by_provider || null, {
            transaction,
        });
        

        

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

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

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

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

        return lab_documents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.document_date !== undefined) updatePayload.document_date = data.document_date;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.reviewed_with_doctor !== undefined) updatePayload.reviewed_with_doctor = data.reviewed_with_doctor;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return lab_documents;
    }

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

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

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


        return lab_documents;
    }

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

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

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

        await lab_documents.destroy({
            transaction
        });

        return lab_documents;
    }

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

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

        if (!lab_documents) {
            return lab_documents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await lab_documents.getUser({
            transaction
        });
        
        
        output.file_attachments = await lab_documents.getFile_attachments({
            transaction
        });
        
        
        output.ordered_by_provider = await lab_documents.getOrdered_by_provider({
            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.healthcare_providers,
        as: 'ordered_by_provider',
        
        where: filter.ordered_by_provider ? {
          [Op.or]: [
            { id: { [Op.in]: filter.ordered_by_provider.split('|').map(term => Utils.uuid(term)) } },
            {
              provider_name: {
                [Op.or]: filter.ordered_by_provider.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lab_documents',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lab_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.reviewed_with_doctor) {
                where = {
                    ...where,
                reviewed_with_doctor: filter.reviewed_with_doctor,
            };
            }
            


      

      



            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.lab_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(
                        'lab_documents',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

