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

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

        const health_metrics = await db.health_metrics.create(
            {
                id: data.id || undefined,
        
        measured_at: data.measured_at
        ||
        null
            ,
            
        metric_type: data.metric_type
        ||
        null
            ,
            
        value_primary: data.value_primary
        ||
        null
            ,
            
        value_secondary: data.value_secondary
        ||
        null
            ,
            
        unit: data.unit
        ||
        null
            ,
            
        panel_json: data.panel_json
        ||
        null
            ,
            
        device_used: data.device_used
        ||
        null
            ,
            
        is_fasting: data.is_fasting
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return health_metrics;
    }
    

    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 health_metricsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                measured_at: item.measured_at
            ||
            null
            ,
            
                metric_type: item.metric_type
            ||
            null
            ,
            
                value_primary: item.value_primary
            ||
            null
            ,
            
                value_secondary: item.value_secondary
            ||
            null
            ,
            
                unit: item.unit
            ||
            null
            ,
            
                panel_json: item.panel_json
            ||
            null
            ,
            
                device_used: item.device_used
            ||
            null
            ,
            
                is_fasting: item.is_fasting
            ||
            false
        
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return health_metrics;
    }

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

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


        

        const updatePayload = {};
        
        if (data.measured_at !== undefined) updatePayload.measured_at = data.measured_at;
        
        
        if (data.metric_type !== undefined) updatePayload.metric_type = data.metric_type;
        
        
        if (data.value_primary !== undefined) updatePayload.value_primary = data.value_primary;
        
        
        if (data.value_secondary !== undefined) updatePayload.value_secondary = data.value_secondary;
        
        
        if (data.unit !== undefined) updatePayload.unit = data.unit;
        
        
        if (data.panel_json !== undefined) updatePayload.panel_json = data.panel_json;
        
        
        if (data.device_used !== undefined) updatePayload.device_used = data.device_used;
        
        
        if (data.is_fasting !== undefined) updatePayload.is_fasting = data.is_fasting;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return health_metrics;
    }

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

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

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


        return health_metrics;
    }

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

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

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

        await health_metrics.destroy({
            transaction
        });

        return health_metrics;
    }

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

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

        if (!health_metrics) {
            return health_metrics;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await health_metrics.getUser({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'health_metrics',
                        'unit',
                        filter.unit,
                    ),
                };
            }
            
            if (filter.panel_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'health_metrics',
                        'panel_json',
                        filter.panel_json,
                    ),
                };
            }
            
            if (filter.device_used) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'health_metrics',
                        'device_used',
                        filter.device_used,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'health_metrics',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

