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

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

        const activity_blocks = await db.activity_blocks.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        program_shift: data.program_shift
        ||
        null
            ,
            
        block_start_datetime: data.block_start_datetime
        ||
        null
            ,
            
        block_end_datetime: data.block_end_datetime
        ||
        null
            ,
            
        block_type: data.block_type
        ||
        null
            ,
            
        details: data.details
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return activity_blocks;
    }
    

    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 activity_blocksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                program_shift: item.program_shift
            ||
            null
            ,
            
                block_start_datetime: item.block_start_datetime
            ||
            null
            ,
            
                block_end_datetime: item.block_end_datetime
            ||
            null
            ,
            
                block_type: item.block_type
            ||
            null
            ,
            
                details: item.details
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return activity_blocks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.program_shift !== undefined) updatePayload.program_shift = data.program_shift;
        
        
        if (data.block_start_datetime !== undefined) updatePayload.block_start_datetime = data.block_start_datetime;
        
        
        if (data.block_end_datetime !== undefined) updatePayload.block_end_datetime = data.block_end_datetime;
        
        
        if (data.block_type !== undefined) updatePayload.block_type = data.block_type;
        
        
        if (data.details !== undefined) updatePayload.details = data.details;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return activity_blocks;
    }

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

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

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


        return activity_blocks;
    }

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

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

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

        await activity_blocks.destroy({
            transaction
        });

        return activity_blocks;
    }

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

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

        if (!activity_blocks) {
            return activity_blocks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.age_group = await activity_blocks.getAge_group({
            transaction
        });
        
        
        output.camp_session = await activity_blocks.getCamp_session({
            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.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}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'activity_blocks',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'activity_blocks',
                        'details',
                        filter.details,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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


      

      



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

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

    
};

