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

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

        const sun_exposure_logs = await db.sun_exposure_logs.create(
            {
                id: data.id || undefined,
        
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        uv_index: data.uv_index
        ||
        null
            ,
            
        time_outdoors_minutes: data.time_outdoors_minutes
        ||
        null
            ,
            
        spf_used: data.spf_used
        ||
        null
            ,
            
        coverage_level: data.coverage_level
        ||
        null
            ,
            
        vitamin_d_estimate_iu: data.vitamin_d_estimate_iu
        ||
        null
            ,
            
        sunburn_occurred: data.sunburn_occurred
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return sun_exposure_logs;
    }
    

    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 sun_exposure_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                uv_index: item.uv_index
            ||
            null
            ,
            
                time_outdoors_minutes: item.time_outdoors_minutes
            ||
            null
            ,
            
                spf_used: item.spf_used
            ||
            null
            ,
            
                coverage_level: item.coverage_level
            ||
            null
            ,
            
                vitamin_d_estimate_iu: item.vitamin_d_estimate_iu
            ||
            null
            ,
            
                sunburn_occurred: item.sunburn_occurred
            ||
            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 sun_exposure_logs = await db.sun_exposure_logs.bulkCreate(sun_exposure_logsData, { transaction });

        // For each item created, replace relation files
        

        return sun_exposure_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.uv_index !== undefined) updatePayload.uv_index = data.uv_index;
        
        
        if (data.time_outdoors_minutes !== undefined) updatePayload.time_outdoors_minutes = data.time_outdoors_minutes;
        
        
        if (data.spf_used !== undefined) updatePayload.spf_used = data.spf_used;
        
        
        if (data.coverage_level !== undefined) updatePayload.coverage_level = data.coverage_level;
        
        
        if (data.vitamin_d_estimate_iu !== undefined) updatePayload.vitamin_d_estimate_iu = data.vitamin_d_estimate_iu;
        
        
        if (data.sunburn_occurred !== undefined) updatePayload.sunburn_occurred = data.sunburn_occurred;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return sun_exposure_logs;
    }

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

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

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


        return sun_exposure_logs;
    }

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

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

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

        await sun_exposure_logs.destroy({
            transaction
        });

        return sun_exposure_logs;
    }

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

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

        if (!sun_exposure_logs) {
            return sun_exposure_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await sun_exposure_logs.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.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sun_exposure_logs',
                        'notes',
                        filter.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.uv_indexRange) {
                const [start, end] = filter.uv_indexRange;

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

