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

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

        const weekly_themes = await db.weekly_themes.create(
            {
                id: data.id || undefined,
        
        week_number: data.week_number
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        tagline: data.tagline
        ||
        null
            ,
            
        start_datetime: data.start_datetime
        ||
        null
            ,
            
        end_datetime: data.end_datetime
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await weekly_themes.setCamp_session( data.camp_session || null, {
            transaction,
        });
        

        

        

        return weekly_themes;
    }
    

    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 weekly_themesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                week_number: item.week_number
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                tagline: item.tagline
            ||
            null
            ,
            
                start_datetime: item.start_datetime
            ||
            null
            ,
            
                end_datetime: item.end_datetime
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return weekly_themes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.week_number !== undefined) updatePayload.week_number = data.week_number;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.tagline !== undefined) updatePayload.tagline = data.tagline;
        
        
        if (data.start_datetime !== undefined) updatePayload.start_datetime = data.start_datetime;
        
        
        if (data.end_datetime !== undefined) updatePayload.end_datetime = data.end_datetime;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return weekly_themes;
    }

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

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

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


        return weekly_themes;
    }

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

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

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

        await weekly_themes.destroy({
            transaction
        });

        return weekly_themes;
    }

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

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

        if (!weekly_themes) {
            return weekly_themes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.camp_session = await weekly_themes.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.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.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'weekly_themes',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.tagline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'weekly_themes',
                        'tagline',
                        filter.tagline,
                    ),
                };
            }
            

            
            
            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.week_numberRange) {
                const [start, end] = filter.week_numberRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    week_number: {
                    ...where.week_number,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.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.weekly_themes.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(
                        'weekly_themes',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

