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

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

        const conditions = await db.conditions.create(
            {
                id: data.id || undefined,
        
        condition_name: data.condition_name
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        date_diagnosed: data.date_diagnosed
        ||
        null
            ,
            
        diagnosing_doctor: data.diagnosing_doctor
        ||
        null
            ,
            
        management_plan: data.management_plan
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return conditions;
    }
    

    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 conditionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                condition_name: item.condition_name
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                date_diagnosed: item.date_diagnosed
            ||
            null
            ,
            
                diagnosing_doctor: item.diagnosing_doctor
            ||
            null
            ,
            
                management_plan: item.management_plan
            ||
            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 conditions = await db.conditions.bulkCreate(conditionsData, { transaction });

        // For each item created, replace relation files
        

        return conditions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.condition_name !== undefined) updatePayload.condition_name = data.condition_name;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.date_diagnosed !== undefined) updatePayload.date_diagnosed = data.date_diagnosed;
        
        
        if (data.diagnosing_doctor !== undefined) updatePayload.diagnosing_doctor = data.diagnosing_doctor;
        
        
        if (data.management_plan !== undefined) updatePayload.management_plan = data.management_plan;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return conditions;
    }

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

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

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


        return conditions;
    }

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

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

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

        await conditions.destroy({
            transaction
        });

        return conditions;
    }

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

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

        if (!conditions) {
            return conditions;
        }

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

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

            
            

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

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

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

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

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


      



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

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

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

    
};

