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

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

        const study_sessions = await db.study_sessions.create(
            {
                id: data.id || undefined,
        
        mode: data.mode
        ||
        null
            ,
            
        session_type: data.session_type
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        duration_seconds: data.duration_seconds
        ||
        null
            ,
            
        distraction_block_enabled: data.distraction_block_enabled
        ||
        false
        
            ,
            
        music_mode: data.music_mode
        ||
        null
            ,
            
        focus_score: data.focus_score
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await study_sessions.setUser( data.user || null, {
            transaction,
        });
        
        await study_sessions.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await study_sessions.setSubject( data.subject || null, {
            transaction,
        });
        
        await study_sessions.setTopic( data.topic || null, {
            transaction,
        });
        
        await study_sessions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return study_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 study_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                mode: item.mode
            ||
            null
            ,
            
                session_type: item.session_type
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                duration_seconds: item.duration_seconds
            ||
            null
            ,
            
                distraction_block_enabled: item.distraction_block_enabled
            ||
            false
        
            ,
            
                music_mode: item.music_mode
            ||
            null
            ,
            
                focus_score: item.focus_score
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.mode !== undefined) updatePayload.mode = data.mode;
        
        
        if (data.session_type !== undefined) updatePayload.session_type = data.session_type;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
        
        
        if (data.distraction_block_enabled !== undefined) updatePayload.distraction_block_enabled = data.distraction_block_enabled;
        
        
        if (data.music_mode !== undefined) updatePayload.music_mode = data.music_mode;
        
        
        if (data.focus_score !== undefined) updatePayload.focus_score = data.focus_score;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await study_sessions.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.workspace !== undefined) {
            await study_sessions.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await study_sessions.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.topic !== undefined) {
            await study_sessions.setTopic(
              
              data.topic,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await study_sessions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return study_sessions;
    }

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

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

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


        return study_sessions;
    }

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

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

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

        await study_sessions.destroy({
            transaction
        });

        return study_sessions;
    }

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

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

        if (!study_sessions) {
            return study_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.review_events_session = await study_sessions.getReview_events_session({
            transaction
        });
        
        
        
        
        output.quiz_attempts_session = await study_sessions.getQuiz_attempts_session({
            transaction
        });
        
        
        
        
        
        
        
        
        output.user = await study_sessions.getUser({
            transaction
        });
        
        
        output.workspace = await study_sessions.getWorkspace({
            transaction
        });
        
        
        output.subject = await study_sessions.getSubject({
            transaction
        });
        
        
        output.topic = await study_sessions.getTopic({
            transaction
        });
        
        
        output.organizations = await study_sessions.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

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

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



    ];

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

            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            started_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    ended_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

            
            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.duration_secondsRange) {
                const [start, end] = filter.duration_secondsRange;

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

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

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

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

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

            
            if (filter.mode) {
                where = {
                    ...where,
                mode: filter.mode,
            };
            }
            
            if (filter.session_type) {
                where = {
                    ...where,
                session_type: filter.session_type,
            };
            }
            
            if (filter.distraction_block_enabled) {
                where = {
                    ...where,
                distraction_block_enabled: filter.distraction_block_enabled,
            };
            }
            
            if (filter.music_mode) {
                where = {
                    ...where,
                music_mode: filter.music_mode,
            };
            }
            


      

      

      

      

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

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

        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.study_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(
                        'study_sessions',
                        'mode',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

