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

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

        const learning_modules = await db.learning_modules.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        difficulty: data.difficulty
        ||
        null
            ,
            
        topic: data.topic
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        content: data.content
        ||
        null
            ,
            
        estimated_minutes: data.estimated_minutes
        ||
        null
            ,
            
        published: data.published
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return learning_modules;
    }
    

    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 learning_modulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                difficulty: item.difficulty
            ||
            null
            ,
            
                topic: item.topic
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                content: item.content
            ||
            null
            ,
            
                estimated_minutes: item.estimated_minutes
            ||
            null
            ,
            
                published: item.published
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return learning_modules;
    }

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

        const learning_modules = await db.learning_modules.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.difficulty !== undefined) updatePayload.difficulty = data.difficulty;
        
        
        if (data.topic !== undefined) updatePayload.topic = data.topic;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.content !== undefined) updatePayload.content = data.content;
        
        
        if (data.estimated_minutes !== undefined) updatePayload.estimated_minutes = data.estimated_minutes;
        
        
        if (data.published !== undefined) updatePayload.published = data.published;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return learning_modules;
    }

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

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

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


        return learning_modules;
    }

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

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

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

        await learning_modules.destroy({
            transaction
        });

        return learning_modules;
    }

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

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

        if (!learning_modules) {
            return learning_modules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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 = [



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'learning_modules',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'learning_modules',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'learning_modules',
                        'content',
                        filter.content,
                    ),
                };
            }
            

            
            

            
            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.difficulty) {
                where = {
                    ...where,
                difficulty: filter.difficulty,
            };
            }
            
            if (filter.topic) {
                where = {
                    ...where,
                topic: filter.topic,
            };
            }
            
            if (filter.published) {
                where = {
                    ...where,
                published: filter.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.learning_modules.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(
                        'learning_modules',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

