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

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

        const cognitive_programs = await db.cognitive_programs.create(
            {
                id: data.id || undefined,
        
        program_name: data.program_name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        target_stage: data.target_stage
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        estimated_minutes: data.estimated_minutes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cognitive_programs.setCreated_by_user( data.created_by_user || null, {
            transaction,
        });
        
        await cognitive_programs.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return cognitive_programs;
    }
    

    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_programsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                program_name: item.program_name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                target_stage: item.target_stage
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                estimated_minutes: item.estimated_minutes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return cognitive_programs;
    }

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


        

        const updatePayload = {};
        
        if (data.program_name !== undefined) updatePayload.program_name = data.program_name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.target_stage !== undefined) updatePayload.target_stage = data.target_stage;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.estimated_minutes !== undefined) updatePayload.estimated_minutes = data.estimated_minutes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.created_by_user !== undefined) {
            await cognitive_programs.setCreated_by_user(
              
              data.created_by_user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await cognitive_programs.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return cognitive_programs;
    }

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

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

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


        return cognitive_programs;
    }

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

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

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

        await cognitive_programs.destroy({
            transaction
        });

        return cognitive_programs;
    }

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

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

        if (!cognitive_programs) {
            return cognitive_programs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.cognitive_exercises_program = await cognitive_programs.getCognitive_exercises_program({
            transaction
        });
        
        
        output.cognitive_sessions_program = await cognitive_programs.getCognitive_sessions_program({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.created_by_user = await cognitive_programs.getCreated_by_user({
            transaction
        });
        
        
        output.accounts = await cognitive_programs.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.users,
        as: 'created_by_user',
        
        where: filter.created_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.created_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.program_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cognitive_programs',
                        'program_name',
                        filter.program_name,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cognitive_programs',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.target_stage) {
                where = {
                    ...where,
                target_stage: filter.target_stage,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.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_programs.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_programs',
                        'program_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

