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

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

        const field_trip_events = await db.field_trip_events.create(
            {
                id: data.id || undefined,
        
        depart_datetime: data.depart_datetime
        ||
        null
            ,
            
        return_datetime: data.return_datetime
        ||
        null
            ,
            
        price_per_student: data.price_per_student
        ||
        null
            ,
            
        capacity: data.capacity
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await field_trip_events.setCamp_session( data.camp_session || null, {
            transaction,
        });
        
        await field_trip_events.setField_trip( data.field_trip || null, {
            transaction,
        });
        
        await field_trip_events.setAge_group( data.age_group || null, {
            transaction,
        });
        

        

        

        return field_trip_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 field_trip_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                depart_datetime: item.depart_datetime
            ||
            null
            ,
            
                return_datetime: item.return_datetime
            ||
            null
            ,
            
                price_per_student: item.price_per_student
            ||
            null
            ,
            
                capacity: item.capacity
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return field_trip_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.depart_datetime !== undefined) updatePayload.depart_datetime = data.depart_datetime;
        
        
        if (data.return_datetime !== undefined) updatePayload.return_datetime = data.return_datetime;
        
        
        if (data.price_per_student !== undefined) updatePayload.price_per_student = data.price_per_student;
        
        
        if (data.capacity !== undefined) updatePayload.capacity = data.capacity;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.camp_session !== undefined) {
            await field_trip_events.setCamp_session(
              
              data.camp_session,
              
              { transaction }
            );
        }
        
        if (data.field_trip !== undefined) {
            await field_trip_events.setField_trip(
              
              data.field_trip,
              
              { transaction }
            );
        }
        
        if (data.age_group !== undefined) {
            await field_trip_events.setAge_group(
              
              data.age_group,
              
              { transaction }
            );
        }
        

        
        

        

        return field_trip_events;
    }

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

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

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


        return field_trip_events;
    }

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

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

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

        await field_trip_events.destroy({
            transaction
        });

        return field_trip_events;
    }

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

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

        if (!field_trip_events) {
            return field_trip_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.trip_registrations_field_trip_event = await field_trip_events.getTrip_registrations_field_trip_event({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.camp_session = await field_trip_events.getCamp_session({
            transaction
        });
        
        
        output.field_trip = await field_trip_events.getField_trip({
            transaction
        });
        
        
        output.age_group = await field_trip_events.getAge_group({
            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.camp_sessions,
        as: 'camp_session',
        
        where: filter.camp_session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.camp_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    price_per_student: {
                    ...where.price_per_student,
                            [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.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.field_trip_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(
                        'field_trip_events',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

    
};

