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

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

        const medical_chronology_reports = await db.medical_chronology_reports.create(
            {
                id: data.id || undefined,
        
        report_title: data.report_title
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        overview: data.overview
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medical_chronology_reports.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await medical_chronology_reports.setMatter( data.matter || null, {
            transaction,
        });
        
        await medical_chronology_reports.setExport_file( data.export_file || null, {
            transaction,
        });
        

        
        await medical_chronology_reports.setSource_files(data.source_files || [], {
            transaction,
        });
        

        

        return medical_chronology_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_chronology_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                report_title: item.report_title
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                overview: item.overview
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return medical_chronology_reports;
    }

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

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


        

        const updatePayload = {};
        
        if (data.report_title !== undefined) updatePayload.report_title = data.report_title;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.overview !== undefined) updatePayload.overview = data.overview;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requested_by !== undefined) {
            await medical_chronology_reports.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.matter !== undefined) {
            await medical_chronology_reports.setMatter(
              
              data.matter,
              
              { transaction }
            );
        }
        
        if (data.export_file !== undefined) {
            await medical_chronology_reports.setExport_file(
              
              data.export_file,
              
              { transaction }
            );
        }
        

        
        
        if (data.source_files !== undefined) {
            await medical_chronology_reports.setSource_files(data.source_files, { transaction });
        }
        

        

        return medical_chronology_reports;
    }

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

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

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


        return medical_chronology_reports;
    }

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

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

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

        await medical_chronology_reports.destroy({
            transaction
        });

        return medical_chronology_reports;
    }

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

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

        if (!medical_chronology_reports) {
            return medical_chronology_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.medical_events_report = await medical_chronology_reports.getMedical_events_report({
            transaction
        });
        
        
        
        
        
        output.requested_by = await medical_chronology_reports.getRequested_by({
            transaction
        });
        
        
        output.matter = await medical_chronology_reports.getMatter({
            transaction
        });
        
        
        output.source_files = await medical_chronology_reports.getSource_files({
            transaction
        });
        
        
        output.export_file = await medical_chronology_reports.getExport_file({
            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: 'requested_by',
        
        where: filter.requested_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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


      {
        model: db.files,
        as: 'source_files',
        required: false,
      },


    ];

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

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

            
            

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

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

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

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

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


      

      

      


      if (filter.source_files) {
        const searchTerms = filter.source_files.split('|');

        include = [
          {
            model: db.files,
            as: 'source_files_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  file_name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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_chronology_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_chronology_reports',
                        'report_title',
                        query,
                    ),
                ],
            };
        }

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

    
};

