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

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

        const mole_lesion_logs = await db.mole_lesion_logs.create(
            {
                id: data.id || undefined,
        
        lesion_name: data.lesion_name
        ||
        null
            ,
            
        body_location: data.body_location
        ||
        null
            ,
            
        photo_date: data.photo_date
        ||
        null
            ,
            
        monitoring_interval: data.monitoring_interval
        ||
        null
            ,
            
        next_check_due: data.next_check_due
        ||
        null
            ,
            
        abcde_notes: data.abcde_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return mole_lesion_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 mole_lesion_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                lesion_name: item.lesion_name
            ||
            null
            ,
            
                body_location: item.body_location
            ||
            null
            ,
            
                photo_date: item.photo_date
            ||
            null
            ,
            
                monitoring_interval: item.monitoring_interval
            ||
            null
            ,
            
                next_check_due: item.next_check_due
            ||
            null
            ,
            
                abcde_notes: item.abcde_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return mole_lesion_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.lesion_name !== undefined) updatePayload.lesion_name = data.lesion_name;
        
        
        if (data.body_location !== undefined) updatePayload.body_location = data.body_location;
        
        
        if (data.photo_date !== undefined) updatePayload.photo_date = data.photo_date;
        
        
        if (data.monitoring_interval !== undefined) updatePayload.monitoring_interval = data.monitoring_interval;
        
        
        if (data.next_check_due !== undefined) updatePayload.next_check_due = data.next_check_due;
        
        
        if (data.abcde_notes !== undefined) updatePayload.abcde_notes = data.abcde_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return mole_lesion_logs;
    }

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

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

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


        return mole_lesion_logs;
    }

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

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

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

        await mole_lesion_logs.destroy({
            transaction
        });

        return mole_lesion_logs;
    }

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

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

        if (!mole_lesion_logs) {
            return mole_lesion_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await mole_lesion_logs.getUser({
            transaction
        });
        
        
        output.photos = await mole_lesion_logs.getPhotos({
            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: 'photos',
      },

    ];

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

            
            if (filter.lesion_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mole_lesion_logs',
                        'lesion_name',
                        filter.lesion_name,
                    ),
                };
            }
            
            if (filter.abcde_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mole_lesion_logs',
                        'abcde_notes',
                        filter.abcde_notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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


      



            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.mole_lesion_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(
                        'mole_lesion_logs',
                        'lesion_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

