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

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

        const lesson_plans = await db.lesson_plans.create(
            {
                id: data.id || undefined,
        
        week_start_at: data.week_start_at
        ||
        null
            ,
            
        week_end_at: data.week_end_at
        ||
        null
            ,
            
        plan_content: data.plan_content
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.lesson_plans.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: lesson_plans.id,
            },
            data.attachments,
            options,
        );
        

        return lesson_plans;
    }
    

    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 lesson_plansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                week_start_at: item.week_start_at
            ||
            null
            ,
            
                week_end_at: item.week_end_at
            ||
            null
            ,
            
                plan_content: item.plan_content
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < lesson_plans.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.lesson_plans.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: lesson_plans[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return lesson_plans;
    }

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

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


        

        const updatePayload = {};
        
        if (data.week_start_at !== undefined) updatePayload.week_start_at = data.week_start_at;
        
        
        if (data.week_end_at !== undefined) updatePayload.week_end_at = data.week_end_at;
        
        
        if (data.plan_content !== undefined) updatePayload.plan_content = data.plan_content;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.lesson_plans.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: lesson_plans.id,
            },
            data.attachments,
            options,
        );
        

        return lesson_plans;
    }

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

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

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


        return lesson_plans;
    }

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

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

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

        await lesson_plans.destroy({
            transaction
        });

        return lesson_plans;
    }

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

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

        if (!lesson_plans) {
            return lesson_plans;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.teacher = await lesson_plans.getTeacher({
            transaction
        });
        
        
        output.class_section = await lesson_plans.getClass_section({
            transaction
        });
        
        
        output.subject = await lesson_plans.getSubject({
            transaction
        });
        
        
        output.attachments = await lesson_plans.getAttachments({
            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.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}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.file,
        as: 'attachments',
      },

    ];

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

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

