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

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

        const stage_assessments = await db.stage_assessments.create(
            {
                id: data.id || undefined,
        
        assessed_at: data.assessed_at
        ||
        null
            ,
            
        predicted_stage: data.predicted_stage
        ||
        null
            ,
            
        confidence_score: data.confidence_score
        ||
        null
            ,
            
        method: data.method
        ||
        null
            ,
            
        model_version: data.model_version
        ||
        null
            ,
            
        explanation: data.explanation
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await stage_assessments.setPatient( data.patient || null, {
            transaction,
        });
        
        await stage_assessments.setReviewed_by_user( data.reviewed_by_user || null, {
            transaction,
        });
        
        await stage_assessments.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return stage_assessments;
    }
    

    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 stage_assessmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                assessed_at: item.assessed_at
            ||
            null
            ,
            
                predicted_stage: item.predicted_stage
            ||
            null
            ,
            
                confidence_score: item.confidence_score
            ||
            null
            ,
            
                method: item.method
            ||
            null
            ,
            
                model_version: item.model_version
            ||
            null
            ,
            
                explanation: item.explanation
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return stage_assessments;
    }

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


        

        const updatePayload = {};
        
        if (data.assessed_at !== undefined) updatePayload.assessed_at = data.assessed_at;
        
        
        if (data.predicted_stage !== undefined) updatePayload.predicted_stage = data.predicted_stage;
        
        
        if (data.confidence_score !== undefined) updatePayload.confidence_score = data.confidence_score;
        
        
        if (data.method !== undefined) updatePayload.method = data.method;
        
        
        if (data.model_version !== undefined) updatePayload.model_version = data.model_version;
        
        
        if (data.explanation !== undefined) updatePayload.explanation = data.explanation;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await stage_assessments.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.reviewed_by_user !== undefined) {
            await stage_assessments.setReviewed_by_user(
              
              data.reviewed_by_user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await stage_assessments.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return stage_assessments;
    }

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

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

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


        return stage_assessments;
    }

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

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

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

        await stage_assessments.destroy({
            transaction
        });

        return stage_assessments;
    }

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

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

        if (!stage_assessments) {
            return stage_assessments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await stage_assessments.getPatient({
            transaction
        });
        
        
        output.reviewed_by_user = await stage_assessments.getReviewed_by_user({
            transaction
        });
        
        
        output.accounts = await stage_assessments.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: 'reviewed_by_user',
        
        where: filter.reviewed_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.reviewed_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.reviewed_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.model_version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stage_assessments',
                        'model_version',
                        filter.model_version,
                    ),
                };
            }
            
            if (filter.explanation) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stage_assessments',
                        'explanation',
                        filter.explanation,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

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

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

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

    
};

