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

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

        const cardio_sessions = await db.cardio_sessions.create(
            {
                id: data.id || undefined,
        
        activity_type: data.activity_type
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        duration_minutes: data.duration_minutes
        ||
        null
            ,
            
        distance_km: data.distance_km
        ||
        null
            ,
            
        avg_heart_rate: data.avg_heart_rate
        ||
        null
            ,
            
        perceived_effort: data.perceived_effort
        ||
        null
            ,
            
        calories: data.calories
        ||
        null
            ,
            
        route_notes: data.route_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cardio_sessions.setUser( data.user || null, {
            transaction,
        });
        

        

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

        return cardio_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 cardio_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                activity_type: item.activity_type
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                duration_minutes: item.duration_minutes
            ||
            null
            ,
            
                distance_km: item.distance_km
            ||
            null
            ,
            
                avg_heart_rate: item.avg_heart_rate
            ||
            null
            ,
            
                perceived_effort: item.perceived_effort
            ||
            null
            ,
            
                calories: item.calories
            ||
            null
            ,
            
                route_notes: item.route_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return cardio_sessions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.activity_type !== undefined) updatePayload.activity_type = data.activity_type;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.duration_minutes !== undefined) updatePayload.duration_minutes = data.duration_minutes;
        
        
        if (data.distance_km !== undefined) updatePayload.distance_km = data.distance_km;
        
        
        if (data.avg_heart_rate !== undefined) updatePayload.avg_heart_rate = data.avg_heart_rate;
        
        
        if (data.perceived_effort !== undefined) updatePayload.perceived_effort = data.perceived_effort;
        
        
        if (data.calories !== undefined) updatePayload.calories = data.calories;
        
        
        if (data.route_notes !== undefined) updatePayload.route_notes = data.route_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await cardio_sessions.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

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

        return cardio_sessions;
    }

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

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

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


        return cardio_sessions;
    }

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

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

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

        await cardio_sessions.destroy({
            transaction
        });

        return cardio_sessions;
    }

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

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

        if (!cardio_sessions) {
            return cardio_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await cardio_sessions.getUser({
            transaction
        });
        
        
        output.gps_route_file = await cardio_sessions.getGps_route_file({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      



            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.cardio_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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'cardio_sessions',
                        'route_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

