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

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

        const study_groups = await db.study_groups.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        member_limit: data.member_limit
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await study_groups.setSubject( data.subject || null, {
            transaction,
        });
        
        await study_groups.setOwner( data.owner || null, {
            transaction,
        });
        

        

        

        return study_groups;
    }
    

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

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

        // For each item created, replace relation files
        

        return study_groups;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.member_limit !== undefined) updatePayload.member_limit = data.member_limit;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.subject !== undefined) {
            await study_groups.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.owner !== undefined) {
            await study_groups.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        

        
        

        

        return study_groups;
    }

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

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

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


        return study_groups;
    }

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

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

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

        await study_groups.destroy({
            transaction
        });

        return study_groups;
    }

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

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

        if (!study_groups) {
            return study_groups;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.study_group_memberships_study_group = await study_groups.getStudy_group_memberships_study_group({
            transaction
        });
        
        
        output.study_group_posts_study_group = await study_groups.getStudy_group_posts_study_group({
            transaction
        });
        
        
        output.study_group_messages_study_group = await study_groups.getStudy_group_messages_study_group({
            transaction
        });
        
        
        output.study_group_resources_study_group = await study_groups.getStudy_group_resources_study_group({
            transaction
        });
        
        
        
        
        
        
        output.subject = await study_groups.getSubject({
            transaction
        });
        
        
        output.owner = await study_groups.getOwner({
            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.subjects,
        as: 'subject',
        
        where: filter.subject ? {
          [Op.or]: [
            { id: { [Op.in]: filter.subject.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.subject.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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


      

      



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

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

    
};

