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

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

        const adviser_reports = await db.adviser_reports.create(
            {
                id: data.id || undefined,
        
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        report_status: data.report_status
        ||
        null
            ,
            
        summary_notes: data.summary_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await adviser_reports.setGradebook( data.gradebook || null, {
            transaction,
        });
        
        await adviser_reports.setAdviser_teacher( data.adviser_teacher || null, {
            transaction,
        });
        
        await adviser_reports.setSubmitted_by_teacher( data.submitted_by_teacher || null, {
            transaction,
        });
        
        await adviser_reports.setSchools( data.schools || null, {
            transaction,
        });
        

        

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

        return adviser_reports;
    }
    

    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 adviser_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                report_status: item.report_status
            ||
            null
            ,
            
                summary_notes: item.summary_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return adviser_reports;
    }

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


        

        const updatePayload = {};
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.report_status !== undefined) updatePayload.report_status = data.report_status;
        
        
        if (data.summary_notes !== undefined) updatePayload.summary_notes = data.summary_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.gradebook !== undefined) {
            await adviser_reports.setGradebook(
              
              data.gradebook,
              
              { transaction }
            );
        }
        
        if (data.adviser_teacher !== undefined) {
            await adviser_reports.setAdviser_teacher(
              
              data.adviser_teacher,
              
              { transaction }
            );
        }
        
        if (data.submitted_by_teacher !== undefined) {
            await adviser_reports.setSubmitted_by_teacher(
              
              data.submitted_by_teacher,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await adviser_reports.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

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

        return adviser_reports;
    }

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

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

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


        return adviser_reports;
    }

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

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

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

        await adviser_reports.destroy({
            transaction
        });

        return adviser_reports;
    }

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

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

        if (!adviser_reports) {
            return adviser_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.gradebook = await adviser_reports.getGradebook({
            transaction
        });
        
        
        output.adviser_teacher = await adviser_reports.getAdviser_teacher({
            transaction
        });
        
        
        output.submitted_by_teacher = await adviser_reports.getSubmitted_by_teacher({
            transaction
        });
        
        
        output.report_files = await adviser_reports.getReport_files({
            transaction
        });
        
        
        output.schools = await adviser_reports.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.gradebooks,
        as: 'gradebook',
        
        where: filter.gradebook ? {
          [Op.or]: [
            { id: { [Op.in]: filter.gradebook.split('|').map(term => Utils.uuid(term)) } },
            {
              gradebook_name: {
                [Op.or]: filter.gradebook.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



      {
        model: db.file,
        as: 'report_files',
      },

    ];

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

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

            
            

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

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

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

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

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


      

      

      

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

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

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

    
};

