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

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

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

        
        await study_group_resources.setStudy_group( data.study_group || null, {
            transaction,
        });
        
        await study_group_resources.setAdded_by( data.added_by || null, {
            transaction,
        });
        

        

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

        return study_group_resources;
    }
    

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

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

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

        return study_group_resources;
    }

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

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


        

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

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

        
        
        if (data.study_group !== undefined) {
            await study_group_resources.setStudy_group(
              
              data.study_group,
              
              { transaction }
            );
        }
        
        if (data.added_by !== undefined) {
            await study_group_resources.setAdded_by(
              
              data.added_by,
              
              { transaction }
            );
        }
        

        
        

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

        return study_group_resources;
    }

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

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

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


        return study_group_resources;
    }

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

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

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

        await study_group_resources.destroy({
            transaction
        });

        return study_group_resources;
    }

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

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

        if (!study_group_resources) {
            return study_group_resources;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.study_group = await study_group_resources.getStudy_group({
            transaction
        });
        
        
        output.added_by = await study_group_resources.getAdded_by({
            transaction
        });
        
        
        output.files = await study_group_resources.getFiles({
            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.study_groups,
        as: 'study_group',
        
        where: filter.study_group ? {
          [Op.or]: [
            { id: { [Op.in]: filter.study_group.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.study_group.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'study_group_resources',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'study_group_resources',
                        'url',
                        filter.url,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'study_group_resources',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            

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

            


      

      



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

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

    
};

