
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_date: data.report_date
        ||
        null
            ,
            
        report_type: data.report_type
        ||
        null
            ,
            
        chief_complaint: data.chief_complaint
        ||
        null
            ,
            
        symptoms: data.symptoms
        ||
        null
            ,
            
        diagnosis: data.diagnosis
        ||
        null
            ,
            
        clinical_notes: data.clinical_notes
        ||
        null
            ,
            
        prescription_notes: data.prescription_notes
        ||
        null
            ,
            
        recommended_tests: data.recommended_tests
        ||
        null
            ,
            
        is_finalized: data.is_finalized
        ||
        false
        
            ,
            
        finalized_at: data.finalized_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medical_reports.setPatient( data.patient || null, {
            transaction,
        });
        
        await medical_reports.setAuthor_city_doctor( data.author_city_doctor || null, {
            transaction,
        });
        
        await medical_reports.setAuthor_rural_doctor( data.author_rural_doctor || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.medical_reports.getTableName(),
                belongsToColumn: 'attachments_files',
                belongsToId: medical_reports.id,
            },
            data.attachments_files,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.medical_reports.getTableName(),
                belongsToColumn: 'pdf_report_files',
                belongsToId: medical_reports.id,
            },
            data.pdf_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_date: item.report_date
            ||
            null
            ,
            
                report_type: item.report_type
            ||
            null
            ,
            
                chief_complaint: item.chief_complaint
            ||
            null
            ,
            
                symptoms: item.symptoms
            ||
            null
            ,
            
                diagnosis: item.diagnosis
            ||
            null
            ,
            
                clinical_notes: item.clinical_notes
            ||
            null
            ,
            
                prescription_notes: item.prescription_notes
            ||
            null
            ,
            
                recommended_tests: item.recommended_tests
            ||
            null
            ,
            
                is_finalized: item.is_finalized
            ||
            false
        
            ,
            
                finalized_at: item.finalized_at
            ||
            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: 'attachments_files',
                    belongsToId: medical_reports[i].id,
                },
                data[i].attachments_files,
                options,
            );
        }
        
        for (let i = 0; i < medical_reports.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.medical_reports.getTableName(),
                    belongsToColumn: 'pdf_report_files',
                    belongsToId: medical_reports[i].id,
                },
                data[i].pdf_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 medical_reports = await db.medical_reports.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.report_date !== undefined) updatePayload.report_date = data.report_date;
        
        
        if (data.report_type !== undefined) updatePayload.report_type = data.report_type;
        
        
        if (data.chief_complaint !== undefined) updatePayload.chief_complaint = data.chief_complaint;
        
        
        if (data.symptoms !== undefined) updatePayload.symptoms = data.symptoms;
        
        
        if (data.diagnosis !== undefined) updatePayload.diagnosis = data.diagnosis;
        
        
        if (data.clinical_notes !== undefined) updatePayload.clinical_notes = data.clinical_notes;
        
        
        if (data.prescription_notes !== undefined) updatePayload.prescription_notes = data.prescription_notes;
        
        
        if (data.recommended_tests !== undefined) updatePayload.recommended_tests = data.recommended_tests;
        
        
        if (data.is_finalized !== undefined) updatePayload.is_finalized = data.is_finalized;
        
        
        if (data.finalized_at !== undefined) updatePayload.finalized_at = data.finalized_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await medical_reports.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.author_city_doctor !== undefined) {
            await medical_reports.setAuthor_city_doctor(
              
              data.author_city_doctor,
              
              { transaction }
            );
        }
        
        if (data.author_rural_doctor !== undefined) {
            await medical_reports.setAuthor_rural_doctor(
              
              data.author_rural_doctor,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.medical_reports.getTableName(),
                belongsToColumn: 'attachments_files',
                belongsToId: medical_reports.id,
            },
            data.attachments_files,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.medical_reports.getTableName(),
                belongsToColumn: 'pdf_report_files',
                belongsToId: medical_reports.id,
            },
            data.pdf_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.medicine_reminders_medical_report = await medical_reports.getMedicine_reminders_medical_report({
            transaction
        });
        
        
        
        
        
        
        output.patient = await medical_reports.getPatient({
            transaction
        });
        
        
        output.author_city_doctor = await medical_reports.getAuthor_city_doctor({
            transaction
        });
        
        
        output.author_rural_doctor = await medical_reports.getAuthor_rural_doctor({
            transaction
        });
        
        
        output.attachments_files = await medical_reports.getAttachments_files({
            transaction
        });
        
        
        output.pdf_report_files = await medical_reports.getPdf_report_files({
            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.patients,
        as: 'patient',
        
        where: filter.patient ? {
          [Op.or]: [
            { id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

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

    ];

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

            
            if (filter.chief_complaint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_reports',
                        'chief_complaint',
                        filter.chief_complaint,
                    ),
                };
            }
            
            if (filter.symptoms) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_reports',
                        'symptoms',
                        filter.symptoms,
                    ),
                };
            }
            
            if (filter.diagnosis) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_reports',
                        'diagnosis',
                        filter.diagnosis,
                    ),
                };
            }
            
            if (filter.clinical_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_reports',
                        'clinical_notes',
                        filter.clinical_notes,
                    ),
                };
            }
            
            if (filter.prescription_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_reports',
                        'prescription_notes',
                        filter.prescription_notes,
                    ),
                };
            }
            
            if (filter.recommended_tests) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_reports',
                        'recommended_tests',
                        filter.recommended_tests,
                    ),
                };
            }
            

            
            

            
            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.finalized_atRange) {
                const [start, end] = filter.finalized_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    finalized_at: {
                    ...where.finalized_at,
                            [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.is_finalized) {
                where = {
                    ...where,
                is_finalized: filter.is_finalized,
            };
            }
            


      

      

      



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

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

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

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

    
};

