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

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

        const events = await db.events.create(
            {
                id: data.id || undefined,
        
        title_text: data.title_text
        ||
        null
            ,
            
        description_text: data.description_text
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        location_text: data.location_text
        ||
        null
            ,
            
        online_url: data.online_url
        ||
        null
            ,
            
        starts_at: data.starts_at
        ||
        null
            ,
            
        ends_at: data.ends_at
        ||
        null
            ,
            
        capacity: data.capacity
        ||
        null
            ,
            
        requires_ticket: data.requires_ticket
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await events.setHost( data.host || null, {
            transaction,
        });
        
        await events.setGroup( data.group || null, {
            transaction,
        });
        

        

        

        return 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 eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title_text: item.title_text
            ||
            null
            ,
            
                description_text: item.description_text
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                location_text: item.location_text
            ||
            null
            ,
            
                online_url: item.online_url
            ||
            null
            ,
            
                starts_at: item.starts_at
            ||
            null
            ,
            
                ends_at: item.ends_at
            ||
            null
            ,
            
                capacity: item.capacity
            ||
            null
            ,
            
                requires_ticket: item.requires_ticket
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
        
        
        if (data.description_text !== undefined) updatePayload.description_text = data.description_text;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.location_text !== undefined) updatePayload.location_text = data.location_text;
        
        
        if (data.online_url !== undefined) updatePayload.online_url = data.online_url;
        
        
        if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
        
        
        if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
        
        
        if (data.capacity !== undefined) updatePayload.capacity = data.capacity;
        
        
        if (data.requires_ticket !== undefined) updatePayload.requires_ticket = data.requires_ticket;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.host !== undefined) {
            await events.setHost(
              
              data.host,
              
              { transaction }
            );
        }
        
        if (data.group !== undefined) {
            await events.setGroup(
              
              data.group,
              
              { transaction }
            );
        }
        

        
        

        

        return events;
    }

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

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

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


        return events;
    }

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

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

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

        await events.destroy({
            transaction
        });

        return events;
    }

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

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

        if (!events) {
            return events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.tickets_event = await events.getTickets_event({
            transaction
        });
        
        
        output.notifications_event = await events.getNotifications_event({
            transaction
        });
        
        
        
        
        
        
        
        
        output.transactions_event = await events.getTransactions_event({
            transaction
        });
        
        
        
        
        
        
        
        output.host = await events.getHost({
            transaction
        });
        
        
        output.group = await events.getGroup({
            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.users,
        as: 'host',
        
        where: filter.host ? {
          [Op.or]: [
            { id: { [Op.in]: filter.host.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.host.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.title_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'events',
                        'title_text',
                        filter.title_text,
                    ),
                };
            }
            
            if (filter.description_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'events',
                        'description_text',
                        filter.description_text,
                    ),
                };
            }
            
            if (filter.location_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'events',
                        'location_text',
                        filter.location_text,
                    ),
                };
            }
            
            if (filter.online_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'events',
                        'online_url',
                        filter.online_url,
                    ),
                };
            }
            

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    capacity: {
                    ...where.capacity,
                            [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.requires_ticket) {
                where = {
                    ...where,
                requires_ticket: filter.requires_ticket,
            };
            }
            


      

      



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

        const records = await db.events.findAll({
            attributes: [ 'id', 'title_text' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['title_text', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.title_text,
        }));
    }

    
};

