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

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

        const class_schedules = await db.class_schedules.create(
            {
                id: data.id || undefined,
        
        weekday: data.weekday
        ||
        null
            ,
            
        period_label: data.period_label
        ||
        null
            ,
            
        starts_at: data.starts_at
        ||
        null
            ,
            
        ends_at: data.ends_at
        ||
        null
            ,
            
        room: data.room
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await class_schedules.setClass_section( data.class_section || null, {
            transaction,
        });
        
        await class_schedules.setSubject( data.subject || null, {
            transaction,
        });
        
        await class_schedules.setTeacher( data.teacher || null, {
            transaction,
        });
        

        

        

        return class_schedules;
    }
    

    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 class_schedulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                weekday: item.weekday
            ||
            null
            ,
            
                period_label: item.period_label
            ||
            null
            ,
            
                starts_at: item.starts_at
            ||
            null
            ,
            
                ends_at: item.ends_at
            ||
            null
            ,
            
                room: item.room
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return class_schedules;
    }

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

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


        

        const updatePayload = {};
        
        if (data.weekday !== undefined) updatePayload.weekday = data.weekday;
        
        
        if (data.period_label !== undefined) updatePayload.period_label = data.period_label;
        
        
        if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
        
        
        if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
        
        
        if (data.room !== undefined) updatePayload.room = data.room;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.class_section !== undefined) {
            await class_schedules.setClass_section(
              
              data.class_section,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await class_schedules.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.teacher !== undefined) {
            await class_schedules.setTeacher(
              
              data.teacher,
              
              { transaction }
            );
        }
        

        
        

        

        return class_schedules;
    }

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

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

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


        return class_schedules;
    }

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

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

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

        await class_schedules.destroy({
            transaction
        });

        return class_schedules;
    }

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

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

        if (!class_schedules) {
            return class_schedules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.class_section = await class_schedules.getClass_section({
            transaction
        });
        
        
        output.subject = await class_schedules.getSubject({
            transaction
        });
        
        
        output.teacher = await class_schedules.getTeacher({
            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.class_sections,
        as: 'class_section',
        
        where: filter.class_section ? {
          [Op.or]: [
            { id: { [Op.in]: filter.class_section.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.class_section.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

