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

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

        const coaching_sessions = await db.coaching_sessions.create(
            {
                id: data.id || undefined,
        
        session_type: data.session_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        agenda: data.agenda
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        action_items: data.action_items
        ||
        null
            ,
            
        follow_up_at: data.follow_up_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await coaching_sessions.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await coaching_sessions.setCoach( data.coach || null, {
            transaction,
        });
        
        await coaching_sessions.setCoachee( data.coachee || null, {
            transaction,
        });
        

        

        

        return coaching_sessions;
    }
    

    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 coaching_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                session_type: item.session_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                agenda: item.agenda
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                action_items: item.action_items
            ||
            null
            ,
            
                follow_up_at: item.follow_up_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return coaching_sessions;
    }

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


        

        const updatePayload = {};
        
        if (data.session_type !== undefined) updatePayload.session_type = data.session_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.agenda !== undefined) updatePayload.agenda = data.agenda;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.action_items !== undefined) updatePayload.action_items = data.action_items;
        
        
        if (data.follow_up_at !== undefined) updatePayload.follow_up_at = data.follow_up_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await coaching_sessions.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.coach !== undefined) {
            await coaching_sessions.setCoach(
              
              data.coach,
              
              { transaction }
            );
        }
        
        if (data.coachee !== undefined) {
            await coaching_sessions.setCoachee(
              
              data.coachee,
              
              { transaction }
            );
        }
        

        
        

        

        return coaching_sessions;
    }

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

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

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


        return coaching_sessions;
    }

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

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

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

        await coaching_sessions.destroy({
            transaction
        });

        return coaching_sessions;
    }

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

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

        if (!coaching_sessions) {
            return coaching_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await coaching_sessions.getOrganization({
            transaction
        });
        
        
        output.coach = await coaching_sessions.getCoach({
            transaction
        });
        
        
        output.coachee = await coaching_sessions.getCoachee({
            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.users,
        as: 'coach',
        
        where: filter.coach ? {
          [Op.or]: [
            { id: { [Op.in]: filter.coach.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.coach.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.agenda) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'coaching_sessions',
                        'agenda',
                        filter.agenda,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'coaching_sessions',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            
            if (filter.action_items) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'coaching_sessions',
                        'action_items',
                        filter.action_items,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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


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

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

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

    
};

