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

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

        const timetable_entries = await db.timetable_entries.create(
            {
                id: data.id || undefined,
        
        day_of_week: data.day_of_week
        ||
        null
            ,
            
        period_number: data.period_number
        ||
        null
            ,
            
        start_time: data.start_time
        ||
        null
            ,
            
        end_time: data.end_time
        ||
        null
            ,
            
        room: data.room
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await timetable_entries.setClass( data.class || null, {
            transaction,
        });
        
        await timetable_entries.setClass_subject( data.class_subject || null, {
            transaction,
        });
        
        await timetable_entries.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return timetable_entries;
    }
    

    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 timetable_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                day_of_week: item.day_of_week
            ||
            null
            ,
            
                period_number: item.period_number
            ||
            null
            ,
            
                start_time: item.start_time
            ||
            null
            ,
            
                end_time: item.end_time
            ||
            null
            ,
            
                room: item.room
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return timetable_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.day_of_week !== undefined) updatePayload.day_of_week = data.day_of_week;
        
        
        if (data.period_number !== undefined) updatePayload.period_number = data.period_number;
        
        
        if (data.start_time !== undefined) updatePayload.start_time = data.start_time;
        
        
        if (data.end_time !== undefined) updatePayload.end_time = data.end_time;
        
        
        if (data.room !== undefined) updatePayload.room = data.room;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.class !== undefined) {
            await timetable_entries.setClass(
              
              data.class,
              
              { transaction }
            );
        }
        
        if (data.class_subject !== undefined) {
            await timetable_entries.setClass_subject(
              
              data.class_subject,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await timetable_entries.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return timetable_entries;
    }

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

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

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


        return timetable_entries;
    }

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

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

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

        await timetable_entries.destroy({
            transaction
        });

        return timetable_entries;
    }

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

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

        if (!timetable_entries) {
            return timetable_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.class = await timetable_entries.getClass({
            transaction
        });
        
        
        output.class_subject = await timetable_entries.getClass_subject({
            transaction
        });
        
        
        output.schools = await timetable_entries.getSchools({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userSchools = (user && user.schools?.id) || null;
        

        
        if (userSchools) {
            if (options?.currentUser?.schoolsId) {
                where.schoolsId = options.currentUser.schoolsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

      {
        model: db.schools,
        as: 'schools',
        
      },



    ];

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

            
            if (filter.start_time) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'timetable_entries',
                        'start_time',
                        filter.start_time,
                    ),
                };
            }
            
            if (filter.end_time) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'timetable_entries',
                        'end_time',
                        filter.end_time,
                    ),
                };
            }
            
            if (filter.room) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'timetable_entries',
                        'room',
                        filter.room,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      
      if (filter.schools) {
        const listItems = filter.schools.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          schoolsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.schoolsId;
        }
        

        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.timetable_entries.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'timetable_entries',
                        'room',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

