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

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

        const trip_registrations = await db.trip_registrations.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        permission_granted: data.permission_granted
        ||
        false
        
            ,
            
        registered_datetime: data.registered_datetime
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trip_registrations.setField_trip_event( data.field_trip_event || null, {
            transaction,
        });
        
        await trip_registrations.setEnrollment( data.enrollment || null, {
            transaction,
        });
        

        

        

        return trip_registrations;
    }
    

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

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

        // For each item created, replace relation files
        

        return trip_registrations;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.permission_granted !== undefined) updatePayload.permission_granted = data.permission_granted;
        
        
        if (data.registered_datetime !== undefined) updatePayload.registered_datetime = data.registered_datetime;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.field_trip_event !== undefined) {
            await trip_registrations.setField_trip_event(
              
              data.field_trip_event,
              
              { transaction }
            );
        }
        
        if (data.enrollment !== undefined) {
            await trip_registrations.setEnrollment(
              
              data.enrollment,
              
              { transaction }
            );
        }
        

        
        

        

        return trip_registrations;
    }

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

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

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


        return trip_registrations;
    }

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

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

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

        await trip_registrations.destroy({
            transaction
        });

        return trip_registrations;
    }

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

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

        if (!trip_registrations) {
            return trip_registrations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.field_trip_event = await trip_registrations.getField_trip_event({
            transaction
        });
        
        
        output.enrollment = await trip_registrations.getEnrollment({
            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.field_trip_events,
        as: 'field_trip_event',
        
        where: filter.field_trip_event ? {
          [Op.or]: [
            { id: { [Op.in]: filter.field_trip_event.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.field_trip_event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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


      

      



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

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

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

    
};

