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

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

        const medical_reports = await db.medical_reports.create(
            {
                id: data.id || undefined,
        
        report_type: data.report_type
        ||
        null
            ,
            
        report_date: data.report_date
        ||
        null
            ,
            
        report_title: data.report_title
        ||
        null
            ,
            
        report_notes: data.report_notes
        ||
        null
            ,
            
        qr_payload: data.qr_payload
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medical_reports.setPatient( data.patient || null, {
            transaction,
        });
        
        await medical_reports.setConsultation( data.consultation || null, {
            transaction,
        });
        
        await medical_reports.setAuthor_doctor( data.author_doctor || null, {
            transaction,
        });
        
        await medical_reports.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return medical_reports;
    }
    

    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 medical_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                report_type: item.report_type
            ||
            null
            ,
            
                report_date: item.report_date
            ||
            null
            ,
            
                report_title: item.report_title
            ||
            null
            ,
            
                report_notes: item.report_notes
            ||
            null
            ,
            
                qr_payload: item.qr_payload
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return medical_reports;
    }

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


        

        const updatePayload = {};
        
        if (data.report_type !== undefined) updatePayload.report_type = data.report_type;
        
        
        if (data.report_date !== undefined) updatePayload.report_date = data.report_date;
        
        
        if (data.report_title !== undefined) updatePayload.report_title = data.report_title;
        
        
        if (data.report_notes !== undefined) updatePayload.report_notes = data.report_notes;
        
        
        if (data.qr_payload !== undefined) updatePayload.qr_payload = data.qr_payload;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await medical_reports.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.consultation !== undefined) {
            await medical_reports.setConsultation(
              
              data.consultation,
              
              { transaction }
            );
        }
        
        if (data.author_doctor !== undefined) {
            await medical_reports.setAuthor_doctor(
              
              data.author_doctor,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await medical_reports.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return medical_reports;
    }

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

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

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


        return medical_reports;
    }

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

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

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

        await medical_reports.destroy({
            transaction
        });

        return medical_reports;
    }

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

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

        if (!medical_reports) {
            return medical_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await medical_reports.getPatient({
            transaction
        });
        
        
        output.consultation = await medical_reports.getConsultation({
            transaction
        });
        
        
        output.author_doctor = await medical_reports.getAuthor_doctor({
            transaction
        });
        
        
        output.report_files = await medical_reports.getReport_files({
            transaction
        });
        
        
        output.organizations = await medical_reports.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.patient_profiles,
        as: 'patient',
        
        where: filter.patient ? {
          [Op.or]: [
            { id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
            {
              patient_identifier: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



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

    ];

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

            
            if (filter.report_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_reports',
                        'report_title',
                        filter.report_title,
                    ),
                };
            }
            
            if (filter.report_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_reports',
                        'report_notes',
                        filter.report_notes,
                    ),
                };
            }
            
            if (filter.qr_payload) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_reports',
                        'qr_payload',
                        filter.qr_payload,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      

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

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

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

    
};

