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

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

        const content_items = await db.content_items.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        content_kind: data.content_kind
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        recommended_minutes: data.recommended_minutes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await content_items.setLesson( data.lesson || null, {
            transaction,
        });
        
        await content_items.setExercise( data.exercise || null, {
            transaction,
        });
        
        await content_items.setGame( data.game || null, {
            transaction,
        });
        
        await content_items.setActivity( data.activity || null, {
            transaction,
        });
        
        await content_items.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return content_items;
    }
    

    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 content_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                content_kind: item.content_kind
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                recommended_minutes: item.recommended_minutes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return content_items;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.content_kind !== undefined) updatePayload.content_kind = data.content_kind;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.recommended_minutes !== undefined) updatePayload.recommended_minutes = data.recommended_minutes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.lesson !== undefined) {
            await content_items.setLesson(
              
              data.lesson,
              
              { transaction }
            );
        }
        
        if (data.exercise !== undefined) {
            await content_items.setExercise(
              
              data.exercise,
              
              { transaction }
            );
        }
        
        if (data.game !== undefined) {
            await content_items.setGame(
              
              data.game,
              
              { transaction }
            );
        }
        
        if (data.activity !== undefined) {
            await content_items.setActivity(
              
              data.activity,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await content_items.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return content_items;
    }

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

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

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


        return content_items;
    }

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

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

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

        await content_items.destroy({
            transaction
        });

        return content_items;
    }

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

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

        if (!content_items) {
            return content_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.progress_records_content_item = await content_items.getProgress_records_content_item({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.lesson = await content_items.getLesson({
            transaction
        });
        
        
        output.exercise = await content_items.getExercise({
            transaction
        });
        
        
        output.game = await content_items.getGame({
            transaction
        });
        
        
        output.activity = await content_items.getActivity({
            transaction
        });
        
        
        output.organizations = await content_items.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.lessons,
        as: 'lesson',
        
        where: filter.lesson ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lesson.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.lesson.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.interactive_activities,
        as: 'activity',
        
        where: filter.activity ? {
          [Op.or]: [
            { id: { [Op.in]: filter.activity.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.activity.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.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'content_items',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'content_items',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      

      

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

        const records = await db.content_items.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,
        }));
    }

    
};

