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

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

        const subjects = await db.subjects.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        color_hex: data.color_hex
        ||
        null
            ,
            
        is_archived: data.is_archived
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await subjects.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await subjects.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.subjects.getTableName(),
                belongsToColumn: 'cover_image',
                belongsToId: subjects.id,
            },
            data.cover_image,
            options,
        );
        

        return subjects;
    }
    

    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 subjectsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                color_hex: item.color_hex
            ||
            null
            ,
            
                is_archived: item.is_archived
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < subjects.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.subjects.getTableName(),
                    belongsToColumn: 'cover_image',
                    belongsToId: subjects[i].id,
                },
                data[i].cover_image,
                options,
            );
        }
        

        return subjects;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.color_hex !== undefined) updatePayload.color_hex = data.color_hex;
        
        
        if (data.is_archived !== undefined) updatePayload.is_archived = data.is_archived;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await subjects.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await subjects.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.subjects.getTableName(),
                belongsToColumn: 'cover_image',
                belongsToId: subjects.id,
            },
            data.cover_image,
            options,
        );
        

        return subjects;
    }

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

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

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


        return subjects;
    }

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

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

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

        await subjects.destroy({
            transaction
        });

        return subjects;
    }

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

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

        if (!subjects) {
            return subjects;
        }

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

        
        
        
        
        
        
        
        
        output.topics_subject = await subjects.getTopics_subject({
            transaction
        });
        
        
        output.pages_subject = await subjects.getPages_subject({
            transaction
        });
        
        
        
        
        output.database_entries_subject = await subjects.getDatabase_entries_subject({
            transaction
        });
        
        
        output.sources_subject = await subjects.getSources_subject({
            transaction
        });
        
        
        
        
        
        
        output.flashcard_decks_subject = await subjects.getFlashcard_decks_subject({
            transaction
        });
        
        
        
        
        output.study_sessions_subject = await subjects.getStudy_sessions_subject({
            transaction
        });
        
        
        
        output.quizzes_subject = await subjects.getQuizzes_subject({
            transaction
        });
        
        
        
        
        output.tutor_conversations_subject = await subjects.getTutor_conversations_subject({
            transaction
        });
        
        
        
        
        output.study_plan_items_subject = await subjects.getStudy_plan_items_subject({
            transaction
        });
        
        
        
        
        output.workspace = await subjects.getWorkspace({
            transaction
        });
        
        
        output.cover_image = await subjects.getCover_image({
            transaction
        });
        
        
        output.organizations = await subjects.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.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'cover_image',
      },

    ];

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

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

            
            

            

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

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


      

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

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

    
};

