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

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

        const camp_sessions = await db.camp_sessions.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        theme_title: data.theme_title
        ||
        null
            ,
            
        theme_summary: data.theme_summary
        ||
        null
            ,
            
        theme_scripture_reference: data.theme_scripture_reference
        ||
        null
            ,
            
        theme_scripture_text: data.theme_scripture_text
        ||
        null
            ,
            
        start_datetime: data.start_datetime
        ||
        null
            ,
            
        end_datetime: data.end_datetime
        ||
        null
            ,
            
        day_camp_hours: data.day_camp_hours
        ||
        null
            ,
            
        third_shift_hours: data.third_shift_hours
        ||
        null
            ,
            
        is_published: data.is_published
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await camp_sessions.setCampus( data.campus || null, {
            transaction,
        });
        

        

        

        return camp_sessions;
    }
    

    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 camp_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                theme_title: item.theme_title
            ||
            null
            ,
            
                theme_summary: item.theme_summary
            ||
            null
            ,
            
                theme_scripture_reference: item.theme_scripture_reference
            ||
            null
            ,
            
                theme_scripture_text: item.theme_scripture_text
            ||
            null
            ,
            
                start_datetime: item.start_datetime
            ||
            null
            ,
            
                end_datetime: item.end_datetime
            ||
            null
            ,
            
                day_camp_hours: item.day_camp_hours
            ||
            null
            ,
            
                third_shift_hours: item.third_shift_hours
            ||
            null
            ,
            
                is_published: item.is_published
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return camp_sessions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.theme_title !== undefined) updatePayload.theme_title = data.theme_title;
        
        
        if (data.theme_summary !== undefined) updatePayload.theme_summary = data.theme_summary;
        
        
        if (data.theme_scripture_reference !== undefined) updatePayload.theme_scripture_reference = data.theme_scripture_reference;
        
        
        if (data.theme_scripture_text !== undefined) updatePayload.theme_scripture_text = data.theme_scripture_text;
        
        
        if (data.start_datetime !== undefined) updatePayload.start_datetime = data.start_datetime;
        
        
        if (data.end_datetime !== undefined) updatePayload.end_datetime = data.end_datetime;
        
        
        if (data.day_camp_hours !== undefined) updatePayload.day_camp_hours = data.day_camp_hours;
        
        
        if (data.third_shift_hours !== undefined) updatePayload.third_shift_hours = data.third_shift_hours;
        
        
        if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.campus !== undefined) {
            await camp_sessions.setCampus(
              
              data.campus,
              
              { transaction }
            );
        }
        

        
        

        

        return camp_sessions;
    }

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

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

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


        return camp_sessions;
    }

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

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

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

        await camp_sessions.destroy({
            transaction
        });

        return camp_sessions;
    }

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

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

        if (!camp_sessions) {
            return camp_sessions;
        }

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

        
        
        
        
        
        
        
        output.weekly_themes_camp_session = await camp_sessions.getWeekly_themes_camp_session({
            transaction
        });
        
        
        output.pricing_plans_camp_session = await camp_sessions.getPricing_plans_camp_session({
            transaction
        });
        
        
        output.fee_rules_camp_session = await camp_sessions.getFee_rules_camp_session({
            transaction
        });
        
        
        
        
        output.enrollments_camp_session = await camp_sessions.getEnrollments_camp_session({
            transaction
        });
        
        
        
        output.waiver_documents_camp_session = await camp_sessions.getWaiver_documents_camp_session({
            transaction
        });
        
        
        
        
        output.field_trip_events_camp_session = await camp_sessions.getField_trip_events_camp_session({
            transaction
        });
        
        
        
        output.special_trips_camp_session = await camp_sessions.getSpecial_trips_camp_session({
            transaction
        });
        
        
        output.end_of_summer_trip_options_camp_session = await camp_sessions.getEnd_of_summer_trip_options_camp_session({
            transaction
        });
        
        
        
        output.activity_blocks_camp_session = await camp_sessions.getActivity_blocks_camp_session({
            transaction
        });
        
        
        
        output.staff_assignments_camp_session = await camp_sessions.getStaff_assignments_camp_session({
            transaction
        });
        
        
        output.announcements_camp_session = await camp_sessions.getAnnouncements_camp_session({
            transaction
        });
        
        
        
        output.campus = await camp_sessions.getCampus({
            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.campuses,
        as: 'campus',
        
        where: filter.campus ? {
          [Op.or]: [
            { id: { [Op.in]: filter.campus.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.campus.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'camp_sessions',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.theme_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'camp_sessions',
                        'theme_title',
                        filter.theme_title,
                    ),
                };
            }
            
            if (filter.theme_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'camp_sessions',
                        'theme_summary',
                        filter.theme_summary,
                    ),
                };
            }
            
            if (filter.theme_scripture_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'camp_sessions',
                        'theme_scripture_reference',
                        filter.theme_scripture_reference,
                    ),
                };
            }
            
            if (filter.theme_scripture_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'camp_sessions',
                        'theme_scripture_text',
                        filter.theme_scripture_text,
                    ),
                };
            }
            
            if (filter.day_camp_hours) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'camp_sessions',
                        'day_camp_hours',
                        filter.day_camp_hours,
                    ),
                };
            }
            
            if (filter.third_shift_hours) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'camp_sessions',
                        'third_shift_hours',
                        filter.third_shift_hours,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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


      



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

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

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

    
};

