
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,
        
        lesson_title: data.lesson_title
        ||
        null
            ,
            
        lesson_summary: data.lesson_summary
        ||
        null
            ,
            
        content_format: data.content_format
        ||
        null
            ,
            
        content_body: data.content_body
        ||
        null
            ,
            
        order_index: data.order_index
        ||
        null
            ,
            
        is_published: data.is_published
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await lessons.setCourse( data.course || null, {
            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,
                
                lesson_title: item.lesson_title
            ||
            null
            ,
            
                lesson_summary: item.lesson_summary
            ||
            null
            ,
            
                content_format: item.content_format
            ||
            null
            ,
            
                content_body: item.content_body
            ||
            null
            ,
            
                order_index: item.order_index
            ||
            null
            ,
            
                is_published: item.is_published
            ||
            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 lessons = await db.lessons.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.lesson_title !== undefined) updatePayload.lesson_title = data.lesson_title;
        
        
        if (data.lesson_summary !== undefined) updatePayload.lesson_summary = data.lesson_summary;
        
        
        if (data.content_format !== undefined) updatePayload.content_format = data.content_format;
        
        
        if (data.content_body !== undefined) updatePayload.content_body = data.content_body;
        
        
        if (data.order_index !== undefined) updatePayload.order_index = data.order_index;
        
        
        if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.course !== undefined) {
            await lessons.setCourse(
              
              data.course,
              
              { 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_progress_lesson = await lessons.getLesson_progress_lesson({
            transaction
        });
        
        
        output.artifacts_lesson = await lessons.getArtifacts_lesson({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.course = await lessons.getCourse({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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



    ];

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

            
            if (filter.lesson_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lessons',
                        'lesson_title',
                        filter.lesson_title,
                    ),
                };
            }
            
            if (filter.lesson_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lessons',
                        'lesson_summary',
                        filter.lesson_summary,
                    ),
                };
            }
            
            if (filter.content_body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lessons',
                        'content_body',
                        filter.content_body,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'lessons',
                        'lesson_title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

