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

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

        const lessons = await db.lessons.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        lesson_number: data.lesson_number
        ||
        null
            ,
            
        estimated_minutes: data.estimated_minutes
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        base_content: data.base_content
        ||
        null
            ,
            
        has_quiz: data.has_quiz
        ||
        false
        
            ,
            
        has_build_task: data.has_build_task
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await lessons.setCourse_phase( data.course_phase || null, {
            transaction,
        });
        
        await lessons.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await lessons.setSkill_nodes_awarded(data.skill_nodes_awarded || [], {
            transaction,
        });
        

        

        return lessons;
    }
    

    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 lessonsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                lesson_number: item.lesson_number
            ||
            null
            ,
            
                estimated_minutes: item.estimated_minutes
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                base_content: item.base_content
            ||
            null
            ,
            
                has_quiz: item.has_quiz
            ||
            false
        
            ,
            
                has_build_task: item.has_build_task
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return lessons;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.lesson_number !== undefined) updatePayload.lesson_number = data.lesson_number;
        
        
        if (data.estimated_minutes !== undefined) updatePayload.estimated_minutes = data.estimated_minutes;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.base_content !== undefined) updatePayload.base_content = data.base_content;
        
        
        if (data.has_quiz !== undefined) updatePayload.has_quiz = data.has_quiz;
        
        
        if (data.has_build_task !== undefined) updatePayload.has_build_task = data.has_build_task;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.course_phase !== undefined) {
            await lessons.setCourse_phase(
              
              data.course_phase,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await lessons.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.skill_nodes_awarded !== undefined) {
            await lessons.setSkill_nodes_awarded(data.skill_nodes_awarded, { transaction });
        }
        

        

        return lessons;
    }

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

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

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


        return lessons;
    }

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

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

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

        await lessons.destroy({
            transaction
        });

        return lessons;
    }

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

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

        if (!lessons) {
            return lessons;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.lesson_variants_lesson = await lessons.getLesson_variants_lesson({
            transaction
        });
        
        
        output.quiz_questions_lesson = await lessons.getQuiz_questions_lesson({
            transaction
        });
        
        
        output.build_tasks_lesson = await lessons.getBuild_tasks_lesson({
            transaction
        });
        
        
        
        output.lesson_progress_lesson = await lessons.getLesson_progress_lesson({
            transaction
        });
        
        
        output.quiz_attempts_lesson = await lessons.getQuiz_attempts_lesson({
            transaction
        });
        
        
        
        output.ai_chat_sessions_lesson = await lessons.getAi_chat_sessions_lesson({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.course_phase = await lessons.getCourse_phase({
            transaction
        });
        
        
        output.skill_nodes_awarded = await lessons.getSkill_nodes_awarded({
            transaction
        });
        
        
        output.organizations = await lessons.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.course_phases,
        as: 'course_phase',
        
        where: filter.course_phase ? {
          [Op.or]: [
            { id: { [Op.in]: filter.course_phase.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.course_phase.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.skill_nodes,
        as: 'skill_nodes_awarded',
        required: false,
      },


    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lessons',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lessons',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.base_content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lessons',
                        'base_content',
                        filter.base_content,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    lesson_number: {
                    ...where.lesson_number,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.has_quiz) {
                where = {
                    ...where,
                has_quiz: filter.has_quiz,
            };
            }
            
            if (filter.has_build_task) {
                where = {
                    ...where,
                has_build_task: filter.has_build_task,
            };
            }
            


      

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

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      


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

        include = [
          {
            model: db.skill_nodes,
            as: 'skill_nodes_awarded_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  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,
                        },
                    };
                }
            }
        }
        

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

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

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

    
};

