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

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

        const clinical_reports = await db.clinical_reports.create(
            {
                id: data.id || undefined,
        
        period_start_at: data.period_start_at
        ||
        null
            ,
            
        period_end_at: data.period_end_at
        ||
        null
            ,
            
        report_title: data.report_title
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        share_scope: data.share_scope
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await clinical_reports.setPatient( data.patient || null, {
            transaction,
        });
        
        await clinical_reports.setGenerated_by_user( data.generated_by_user || null, {
            transaction,
        });
        
        await clinical_reports.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

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

        return clinical_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 clinical_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                period_start_at: item.period_start_at
            ||
            null
            ,
            
                period_end_at: item.period_end_at
            ||
            null
            ,
            
                report_title: item.report_title
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                share_scope: item.share_scope
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

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


        

        const updatePayload = {};
        
        if (data.period_start_at !== undefined) updatePayload.period_start_at = data.period_start_at;
        
        
        if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
        
        
        if (data.report_title !== undefined) updatePayload.report_title = data.report_title;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.share_scope !== undefined) updatePayload.share_scope = data.share_scope;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await clinical_reports.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.generated_by_user !== undefined) {
            await clinical_reports.setGenerated_by_user(
              
              data.generated_by_user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await clinical_reports.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

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

        return clinical_reports;
    }

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

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

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


        return clinical_reports;
    }

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

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

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

        await clinical_reports.destroy({
            transaction
        });

        return clinical_reports;
    }

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

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

        if (!clinical_reports) {
            return clinical_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await clinical_reports.getPatient({
            transaction
        });
        
        
        output.generated_by_user = await clinical_reports.getGenerated_by_user({
            transaction
        });
        
        
        output.report_file = await clinical_reports.getReport_file({
            transaction
        });
        
        
        output.accounts = await clinical_reports.getAccounts({
            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 userAccounts = (user && user.accounts?.id) || null;
        

        
        if (userAccounts) {
            if (options?.currentUser?.accountsId) {
                where.accountsId = options.currentUser.accountsId;
            }
        }
        

        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)) } },
            {
              last_name: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    period_start_at: {
                    ...where.period_start_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.period_end_atRange) {
                const [start, end] = filter.period_end_atRange;

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

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

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

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


      

      

      
      if (filter.accounts) {
        const listItems = filter.accounts.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          accountsId: {[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.accountsId;
        }
        

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

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

    
};

