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

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

        const reading_circle_events = await db.reading_circle_events.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        agenda: data.agenda
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        meeting_link: data.meeting_link
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await reading_circle_events.setBook_club( data.book_club || null, {
            transaction,
        });
        
        await reading_circle_events.setBook( data.book || null, {
            transaction,
        });
        

        

        

        return reading_circle_events;
    }
    

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

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

        // For each item created, replace relation files
        

        return reading_circle_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.agenda !== undefined) updatePayload.agenda = data.agenda;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.meeting_link !== undefined) updatePayload.meeting_link = data.meeting_link;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.book_club !== undefined) {
            await reading_circle_events.setBook_club(
              
              data.book_club,
              
              { transaction }
            );
        }
        
        if (data.book !== undefined) {
            await reading_circle_events.setBook(
              
              data.book,
              
              { transaction }
            );
        }
        

        
        

        

        return reading_circle_events;
    }

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

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

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


        return reading_circle_events;
    }

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

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

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

        await reading_circle_events.destroy({
            transaction
        });

        return reading_circle_events;
    }

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

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

        if (!reading_circle_events) {
            return reading_circle_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.book_club = await reading_circle_events.getBook_club({
            transaction
        });
        
        
        output.book = await reading_circle_events.getBook({
            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.book_clubs,
        as: 'book_club',
        
        where: filter.book_club ? {
          [Op.or]: [
            { id: { [Op.in]: filter.book_club.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.book_club.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reading_circle_events',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.agenda) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reading_circle_events',
                        'agenda',
                        filter.agenda,
                    ),
                };
            }
            
            if (filter.meeting_link) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reading_circle_events',
                        'meeting_link',
                        filter.meeting_link,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    start_at: {
                    ...where.start_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.end_atRange) {
                const [start, end] = filter.end_atRange;

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

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

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

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


      

      



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

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

    
};

