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

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

        const timetable_periods = await db.timetable_periods.create(
            {
                id: data.id || undefined,
        
        day_of_week: data.day_of_week
        ||
        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 timetable_periods.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await timetable_periods.setTimetable( data.timetable || null, {
            transaction,
        });
        
        await timetable_periods.setClass_subject( data.class_subject || null, {
            transaction,
        });
        

        

        

        return timetable_periods;
    }
    

    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_periodsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                day_of_week: item.day_of_week
            ||
            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 timetable_periods = await db.timetable_periods.bulkCreate(timetable_periodsData, { transaction });

        // For each item created, replace relation files
        

        return timetable_periods;
    }

    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_periods = await db.timetable_periods.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.day_of_week !== undefined) updatePayload.day_of_week = data.day_of_week;
        
        
        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 timetable_periods.update(updatePayload, {transaction});

        
        
        if (data.organization !== undefined) {
            await timetable_periods.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.timetable !== undefined) {
            await timetable_periods.setTimetable(
              
              data.timetable,
              
              { transaction }
            );
        }
        
        if (data.class_subject !== undefined) {
            await timetable_periods.setClass_subject(
              
              data.class_subject,
              
              { transaction }
            );
        }
        

        
        

        

        return timetable_periods;
    }

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

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

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


        return timetable_periods;
    }

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

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

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

        await timetable_periods.destroy({
            transaction
        });

        return timetable_periods;
    }

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

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

        if (!timetable_periods) {
            return timetable_periods;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await timetable_periods.getOrganization({
            transaction
        });
        
        
        output.timetable = await timetable_periods.getTimetable({
            transaction
        });
        
        
        output.class_subject = await timetable_periods.getClass_subject({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.organizations,
        as: 'organization',
        
      },

      {
        model: db.timetables,
        as: 'timetable',
        
        where: filter.timetable ? {
          [Op.or]: [
            { id: { [Op.in]: filter.timetable.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.timetable.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)) } },
            {
              status: {
                [Op.or]: filter.class_subject.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

            
            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.day_of_week) {
                where = {
                    ...where,
                day_of_week: filter.day_of_week,
            };
            }
            


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

        where = {
          ...where,
          organizationId: {[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.organizationsId;
        }
        

        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_periods.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_periods',
                        'room',
                        query,
                    ),
                ],
            };
        }

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

    
};

