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

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

        const cognitive_sessions = await db.cognitive_sessions.create(
            {
                id: data.id || undefined,
        
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        completion_status: data.completion_status
        ||
        null
            ,
            
        total_score: data.total_score
        ||
        null
            ,
            
        session_notes: data.session_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cognitive_sessions.setPatient( data.patient || null, {
            transaction,
        });
        
        await cognitive_sessions.setProgram( data.program || null, {
            transaction,
        });
        
        await cognitive_sessions.setStarted_by_user( data.started_by_user || null, {
            transaction,
        });
        
        await cognitive_sessions.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return cognitive_sessions;
    }
    

    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 cognitive_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                completion_status: item.completion_status
            ||
            null
            ,
            
                total_score: item.total_score
            ||
            null
            ,
            
                session_notes: item.session_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return cognitive_sessions;
    }

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


        

        const updatePayload = {};
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.completion_status !== undefined) updatePayload.completion_status = data.completion_status;
        
        
        if (data.total_score !== undefined) updatePayload.total_score = data.total_score;
        
        
        if (data.session_notes !== undefined) updatePayload.session_notes = data.session_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await cognitive_sessions.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.program !== undefined) {
            await cognitive_sessions.setProgram(
              
              data.program,
              
              { transaction }
            );
        }
        
        if (data.started_by_user !== undefined) {
            await cognitive_sessions.setStarted_by_user(
              
              data.started_by_user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await cognitive_sessions.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return cognitive_sessions;
    }

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

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

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


        return cognitive_sessions;
    }

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

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

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

        await cognitive_sessions.destroy({
            transaction
        });

        return cognitive_sessions;
    }

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

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

        if (!cognitive_sessions) {
            return cognitive_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cognitive_attempts_session = await cognitive_sessions.getCognitive_attempts_session({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await cognitive_sessions.getPatient({
            transaction
        });
        
        
        output.program = await cognitive_sessions.getProgram({
            transaction
        });
        
        
        output.started_by_user = await cognitive_sessions.getStarted_by_user({
            transaction
        });
        
        
        output.accounts = await cognitive_sessions.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.cognitive_programs,
        as: 'program',
        
        where: filter.program ? {
          [Op.or]: [
            { id: { [Op.in]: filter.program.split('|').map(term => Utils.uuid(term)) } },
            {
              program_name: {
                [Op.or]: filter.program.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'started_by_user',
        
        where: filter.started_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.started_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.started_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.session_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cognitive_sessions',
                        'session_notes',
                        filter.session_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      

      

      

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

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

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

    
};

