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

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

        const nicu_incubators = await db.nicu_incubators.create(
            {
                id: data.id || undefined,
        
        incubator_number: data.incubator_number
        ||
        null
            ,
            
        baby_name: data.baby_name
        ||
        null
            ,
            
        baby_age: data.baby_age
        ||
        null
            ,
            
        medications: data.medications
        ||
        null
            ,
            
        devices: data.devices
        ||
        null
            ,
            
        daily_price: data.daily_price
        ||
        null
            ,
            
        admission_date: data.admission_date
        ||
        null
            ,
            
        discharge_date: data.discharge_date
        ||
        null
            ,
            
        cancellation_reason: data.cancellation_reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await nicu_incubators.setAdmitting_doctor( data.admitting_doctor || null, {
            transaction,
        });
        

        

        

        return nicu_incubators;
    }
    

    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 nicu_incubatorsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                incubator_number: item.incubator_number
            ||
            null
            ,
            
                baby_name: item.baby_name
            ||
            null
            ,
            
                baby_age: item.baby_age
            ||
            null
            ,
            
                medications: item.medications
            ||
            null
            ,
            
                devices: item.devices
            ||
            null
            ,
            
                daily_price: item.daily_price
            ||
            null
            ,
            
                admission_date: item.admission_date
            ||
            null
            ,
            
                discharge_date: item.discharge_date
            ||
            null
            ,
            
                cancellation_reason: item.cancellation_reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return nicu_incubators;
    }

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

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


        

        const updatePayload = {};
        
        if (data.incubator_number !== undefined) updatePayload.incubator_number = data.incubator_number;
        
        
        if (data.baby_name !== undefined) updatePayload.baby_name = data.baby_name;
        
        
        if (data.baby_age !== undefined) updatePayload.baby_age = data.baby_age;
        
        
        if (data.medications !== undefined) updatePayload.medications = data.medications;
        
        
        if (data.devices !== undefined) updatePayload.devices = data.devices;
        
        
        if (data.daily_price !== undefined) updatePayload.daily_price = data.daily_price;
        
        
        if (data.admission_date !== undefined) updatePayload.admission_date = data.admission_date;
        
        
        if (data.discharge_date !== undefined) updatePayload.discharge_date = data.discharge_date;
        
        
        if (data.cancellation_reason !== undefined) updatePayload.cancellation_reason = data.cancellation_reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.admitting_doctor !== undefined) {
            await nicu_incubators.setAdmitting_doctor(
              
              data.admitting_doctor,
              
              { transaction }
            );
        }
        

        
        

        

        return nicu_incubators;
    }

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

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

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


        return nicu_incubators;
    }

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

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

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

        await nicu_incubators.destroy({
            transaction
        });

        return nicu_incubators;
    }

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

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

        if (!nicu_incubators) {
            return nicu_incubators;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.admitting_doctor = await nicu_incubators.getAdmitting_doctor({
            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.doctors,
        as: 'admitting_doctor',
        
        where: filter.admitting_doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.admitting_doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.admitting_doctor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.incubator_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nicu_incubators',
                        'incubator_number',
                        filter.incubator_number,
                    ),
                };
            }
            
            if (filter.baby_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nicu_incubators',
                        'baby_name',
                        filter.baby_name,
                    ),
                };
            }
            
            if (filter.baby_age) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nicu_incubators',
                        'baby_age',
                        filter.baby_age,
                    ),
                };
            }
            
            if (filter.medications) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nicu_incubators',
                        'medications',
                        filter.medications,
                    ),
                };
            }
            
            if (filter.devices) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nicu_incubators',
                        'devices',
                        filter.devices,
                    ),
                };
            }
            
            if (filter.cancellation_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nicu_incubators',
                        'cancellation_reason',
                        filter.cancellation_reason,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            


      



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

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

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

    
};

