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

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

        const nursing_staff = await db.nursing_staff.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        national_number: data.national_number
        ||
        null
            ,
            
        specialty: data.specialty
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        marital_status: data.marital_status
        ||
        null
            ,
            
        children_count: data.children_count
        ||
        null
            ,
            
        night_shifts: data.night_shifts
        ||
        false
        
            ,
            
        salary: data.salary
        ||
        null
            ,
            
        bonuses: data.bonuses
        ||
        null
            ,
            
        hire_date: data.hire_date
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return nursing_staff;
    }
    

    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 nursing_staffData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                national_number: item.national_number
            ||
            null
            ,
            
                specialty: item.specialty
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                marital_status: item.marital_status
            ||
            null
            ,
            
                children_count: item.children_count
            ||
            null
            ,
            
                night_shifts: item.night_shifts
            ||
            false
        
            ,
            
                salary: item.salary
            ||
            null
            ,
            
                bonuses: item.bonuses
            ||
            null
            ,
            
                hire_date: item.hire_date
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return nursing_staff;
    }

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

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


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.national_number !== undefined) updatePayload.national_number = data.national_number;
        
        
        if (data.specialty !== undefined) updatePayload.specialty = data.specialty;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.marital_status !== undefined) updatePayload.marital_status = data.marital_status;
        
        
        if (data.children_count !== undefined) updatePayload.children_count = data.children_count;
        
        
        if (data.night_shifts !== undefined) updatePayload.night_shifts = data.night_shifts;
        
        
        if (data.salary !== undefined) updatePayload.salary = data.salary;
        
        
        if (data.bonuses !== undefined) updatePayload.bonuses = data.bonuses;
        
        
        if (data.hire_date !== undefined) updatePayload.hire_date = data.hire_date;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return nursing_staff;
    }

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

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

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


        return nursing_staff;
    }

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

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

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

        await nursing_staff.destroy({
            transaction
        });

        return nursing_staff;
    }

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

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

        if (!nursing_staff) {
            return nursing_staff;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.room_bookings_supervising_nurse = await nursing_staff.getRoom_bookings_supervising_nurse({
            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 = [



    ];

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

            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nursing_staff',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.national_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nursing_staff',
                        'national_number',
                        filter.national_number,
                    ),
                };
            }
            
            if (filter.specialty) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nursing_staff',
                        'specialty',
                        filter.specialty,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nursing_staff',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'nursing_staff',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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




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

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

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

    
};

