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

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

        const dental_symptoms = await db.dental_symptoms.create(
            {
                id: data.id || undefined,
        
        logged_at: data.logged_at
        ||
        null
            ,
            
        tooth_identifier: data.tooth_identifier
        ||
        null
            ,
            
        symptom_type: data.symptom_type
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return dental_symptoms;
    }
    

    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 dental_symptomsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                logged_at: item.logged_at
            ||
            null
            ,
            
                tooth_identifier: item.tooth_identifier
            ||
            null
            ,
            
                symptom_type: item.symptom_type
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                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 dental_symptoms = await db.dental_symptoms.bulkCreate(dental_symptomsData, { transaction });

        // For each item created, replace relation files
        

        return dental_symptoms;
    }

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

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


        

        const updatePayload = {};
        
        if (data.logged_at !== undefined) updatePayload.logged_at = data.logged_at;
        
        
        if (data.tooth_identifier !== undefined) updatePayload.tooth_identifier = data.tooth_identifier;
        
        
        if (data.symptom_type !== undefined) updatePayload.symptom_type = data.symptom_type;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return dental_symptoms;
    }

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

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

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


        return dental_symptoms;
    }

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

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

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

        await dental_symptoms.destroy({
            transaction
        });

        return dental_symptoms;
    }

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

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

        if (!dental_symptoms) {
            return dental_symptoms;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await dental_symptoms.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.tooth_identifier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'dental_symptoms',
                        'tooth_identifier',
                        filter.tooth_identifier,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'dental_symptoms',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

            
            if (filter.symptom_type) {
                where = {
                    ...where,
                symptom_type: filter.symptom_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.dental_symptoms.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(
                        'dental_symptoms',
                        'tooth_identifier',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

