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

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

        const skill_modules = await db.skill_modules.create(
            {
                id: data.id || undefined,
        
        module_name: data.module_name
        ||
        null
            ,
            
        module_type: data.module_type
        ||
        null
            ,
            
        module_description: data.module_description
        ||
        null
            ,
            
        evidence_level: data.evidence_level
        ||
        null
            ,
            
        method_steps: data.method_steps
        ||
        null
            ,
            
        requires_citations: data.requires_citations
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return skill_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 skill_modulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                module_name: item.module_name
            ||
            null
            ,
            
                module_type: item.module_type
            ||
            null
            ,
            
                module_description: item.module_description
            ||
            null
            ,
            
                evidence_level: item.evidence_level
            ||
            null
            ,
            
                method_steps: item.method_steps
            ||
            null
            ,
            
                requires_citations: item.requires_citations
            ||
            false
        
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return skill_modules;
    }

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

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


        

        const updatePayload = {};
        
        if (data.module_name !== undefined) updatePayload.module_name = data.module_name;
        
        
        if (data.module_type !== undefined) updatePayload.module_type = data.module_type;
        
        
        if (data.module_description !== undefined) updatePayload.module_description = data.module_description;
        
        
        if (data.evidence_level !== undefined) updatePayload.evidence_level = data.evidence_level;
        
        
        if (data.method_steps !== undefined) updatePayload.method_steps = data.method_steps;
        
        
        if (data.requires_citations !== undefined) updatePayload.requires_citations = data.requires_citations;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return skill_modules;
    }

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

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

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


        return skill_modules;
    }

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

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

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

        await skill_modules.destroy({
            transaction
        });

        return skill_modules;
    }

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

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

        if (!skill_modules) {
            return skill_modules;
        }

        const output = skill_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.module_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'skill_modules',
                        'module_name',
                        filter.module_name,
                    ),
                };
            }
            
            if (filter.module_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'skill_modules',
                        'module_description',
                        filter.module_description,
                    ),
                };
            }
            
            if (filter.method_steps) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'skill_modules',
                        'method_steps',
                        filter.method_steps,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.module_type) {
                where = {
                    ...where,
                module_type: filter.module_type,
            };
            }
            
            if (filter.evidence_level) {
                where = {
                    ...where,
                evidence_level: filter.evidence_level,
            };
            }
            
            if (filter.requires_citations) {
                where = {
                    ...where,
                requires_citations: filter.requires_citations,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            




            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.skill_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(
                        'skill_modules',
                        'module_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

