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

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

        const user_physical_baselines = await db.user_physical_baselines.create(
            {
                id: data.id || undefined,
        
        height_cm: data.height_cm
        ||
        null
            ,
            
        height_ft: data.height_ft
        ||
        null
            ,
            
        height_in: data.height_in
        ||
        null
            ,
            
        weight_kg: data.weight_kg
        ||
        null
            ,
            
        weight_lb: data.weight_lb
        ||
        null
            ,
            
        wrist_circumference_cm: data.wrist_circumference_cm
        ||
        null
            ,
            
        dominant_hand: data.dominant_hand
        ||
        null
            ,
            
        fitzpatrick_skin_type: data.fitzpatrick_skin_type
        ||
        null
            ,
            
        blood_type: data.blood_type
        ||
        null
            ,
            
        rh_factor: data.rh_factor
        ||
        null
            ,
            
        body_frame_size: data.body_frame_size
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return user_physical_baselines;
    }
    

    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 user_physical_baselinesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                height_cm: item.height_cm
            ||
            null
            ,
            
                height_ft: item.height_ft
            ||
            null
            ,
            
                height_in: item.height_in
            ||
            null
            ,
            
                weight_kg: item.weight_kg
            ||
            null
            ,
            
                weight_lb: item.weight_lb
            ||
            null
            ,
            
                wrist_circumference_cm: item.wrist_circumference_cm
            ||
            null
            ,
            
                dominant_hand: item.dominant_hand
            ||
            null
            ,
            
                fitzpatrick_skin_type: item.fitzpatrick_skin_type
            ||
            null
            ,
            
                blood_type: item.blood_type
            ||
            null
            ,
            
                rh_factor: item.rh_factor
            ||
            null
            ,
            
                body_frame_size: item.body_frame_size
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return user_physical_baselines;
    }

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

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


        

        const updatePayload = {};
        
        if (data.height_cm !== undefined) updatePayload.height_cm = data.height_cm;
        
        
        if (data.height_ft !== undefined) updatePayload.height_ft = data.height_ft;
        
        
        if (data.height_in !== undefined) updatePayload.height_in = data.height_in;
        
        
        if (data.weight_kg !== undefined) updatePayload.weight_kg = data.weight_kg;
        
        
        if (data.weight_lb !== undefined) updatePayload.weight_lb = data.weight_lb;
        
        
        if (data.wrist_circumference_cm !== undefined) updatePayload.wrist_circumference_cm = data.wrist_circumference_cm;
        
        
        if (data.dominant_hand !== undefined) updatePayload.dominant_hand = data.dominant_hand;
        
        
        if (data.fitzpatrick_skin_type !== undefined) updatePayload.fitzpatrick_skin_type = data.fitzpatrick_skin_type;
        
        
        if (data.blood_type !== undefined) updatePayload.blood_type = data.blood_type;
        
        
        if (data.rh_factor !== undefined) updatePayload.rh_factor = data.rh_factor;
        
        
        if (data.body_frame_size !== undefined) updatePayload.body_frame_size = data.body_frame_size;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return user_physical_baselines;
    }

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

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

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


        return user_physical_baselines;
    }

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

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

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

        await user_physical_baselines.destroy({
            transaction
        });

        return user_physical_baselines;
    }

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

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

        if (!user_physical_baselines) {
            return user_physical_baselines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await user_physical_baselines.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.height_cmRange) {
                const [start, end] = filter.height_cmRange;

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.dominant_hand) {
                where = {
                    ...where,
                dominant_hand: filter.dominant_hand,
            };
            }
            
            if (filter.fitzpatrick_skin_type) {
                where = {
                    ...where,
                fitzpatrick_skin_type: filter.fitzpatrick_skin_type,
            };
            }
            
            if (filter.blood_type) {
                where = {
                    ...where,
                blood_type: filter.blood_type,
            };
            }
            
            if (filter.rh_factor) {
                where = {
                    ...where,
                rh_factor: filter.rh_factor,
            };
            }
            
            if (filter.body_frame_size) {
                where = {
                    ...where,
                body_frame_size: filter.body_frame_size,
            };
            }
            


      



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

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

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

    
};

