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

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

        const notes = await db.notes.create(
            {
                id: data.id || undefined,
        
        tutor_private_notes: data.tutor_private_notes
        ||
        null
            ,
            
        learner_private_notes: data.learner_private_notes
        ||
        null
            ,
            
        shared_notes: data.shared_notes
        ||
        null
            ,
            
        session_summary: data.session_summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await notes.setBooking( data.booking || null, {
            transaction,
        });
        

        

        

        return notes;
    }
    

    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 notesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                tutor_private_notes: item.tutor_private_notes
            ||
            null
            ,
            
                learner_private_notes: item.learner_private_notes
            ||
            null
            ,
            
                shared_notes: item.shared_notes
            ||
            null
            ,
            
                session_summary: item.session_summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return notes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.tutor_private_notes !== undefined) updatePayload.tutor_private_notes = data.tutor_private_notes;
        
        
        if (data.learner_private_notes !== undefined) updatePayload.learner_private_notes = data.learner_private_notes;
        
        
        if (data.shared_notes !== undefined) updatePayload.shared_notes = data.shared_notes;
        
        
        if (data.session_summary !== undefined) updatePayload.session_summary = data.session_summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.booking !== undefined) {
            await notes.setBooking(
              
              data.booking,
              
              { transaction }
            );
        }
        

        
        

        

        return notes;
    }

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

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

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


        return notes;
    }

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

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

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

        await notes.destroy({
            transaction
        });

        return notes;
    }

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

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

        if (!notes) {
            return notes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.booking = await notes.getBooking({
            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.bookings,
        as: 'booking',
        
        where: filter.booking ? {
          [Op.or]: [
            { id: { [Op.in]: filter.booking.split('|').map(term => Utils.uuid(term)) } },
            {
              level_name: {
                [Op.or]: filter.booking.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.tutor_private_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'notes',
                        'tutor_private_notes',
                        filter.tutor_private_notes,
                    ),
                };
            }
            
            if (filter.learner_private_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'notes',
                        'learner_private_notes',
                        filter.learner_private_notes,
                    ),
                };
            }
            
            if (filter.shared_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'notes',
                        'shared_notes',
                        filter.shared_notes,
                    ),
                };
            }
            
            if (filter.session_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'notes',
                        'session_summary',
                        filter.session_summary,
                    ),
                };
            }
            

            
            

            

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

            


      



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

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

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

    
};

