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

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

        const room_bookings = await db.room_bookings.create(
            {
                id: data.id || undefined,
        
        booking_number: data.booking_number
        ||
        null
            ,
            
        admission_date: data.admission_date
        ||
        null
            ,
            
        discharge_date: data.discharge_date
        ||
        null
            ,
            
        days: data.days
        ||
        null
            ,
            
        price_per_day: data.price_per_day
        ||
        null
            ,
            
        total_price: data.total_price
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await room_bookings.setPatient( data.patient || null, {
            transaction,
        });
        
        await room_bookings.setRoom( data.room || null, {
            transaction,
        });
        
        await room_bookings.setSupervising_nurse( data.supervising_nurse || null, {
            transaction,
        });
        
        await room_bookings.setSupervising_doctor( data.supervising_doctor || null, {
            transaction,
        });
        

        

        

        return room_bookings;
    }
    

    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 room_bookingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                booking_number: item.booking_number
            ||
            null
            ,
            
                admission_date: item.admission_date
            ||
            null
            ,
            
                discharge_date: item.discharge_date
            ||
            null
            ,
            
                days: item.days
            ||
            null
            ,
            
                price_per_day: item.price_per_day
            ||
            null
            ,
            
                total_price: item.total_price
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return room_bookings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.booking_number !== undefined) updatePayload.booking_number = data.booking_number;
        
        
        if (data.admission_date !== undefined) updatePayload.admission_date = data.admission_date;
        
        
        if (data.discharge_date !== undefined) updatePayload.discharge_date = data.discharge_date;
        
        
        if (data.days !== undefined) updatePayload.days = data.days;
        
        
        if (data.price_per_day !== undefined) updatePayload.price_per_day = data.price_per_day;
        
        
        if (data.total_price !== undefined) updatePayload.total_price = data.total_price;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await room_bookings.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.room !== undefined) {
            await room_bookings.setRoom(
              
              data.room,
              
              { transaction }
            );
        }
        
        if (data.supervising_nurse !== undefined) {
            await room_bookings.setSupervising_nurse(
              
              data.supervising_nurse,
              
              { transaction }
            );
        }
        
        if (data.supervising_doctor !== undefined) {
            await room_bookings.setSupervising_doctor(
              
              data.supervising_doctor,
              
              { transaction }
            );
        }
        

        
        

        

        return room_bookings;
    }

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

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

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


        return room_bookings;
    }

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

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

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

        await room_bookings.destroy({
            transaction
        });

        return room_bookings;
    }

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

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

        if (!room_bookings) {
            return room_bookings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await room_bookings.getPatient({
            transaction
        });
        
        
        output.room = await room_bookings.getRoom({
            transaction
        });
        
        
        output.supervising_nurse = await room_bookings.getSupervising_nurse({
            transaction
        });
        
        
        output.supervising_doctor = await room_bookings.getSupervising_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.patients,
        as: 'patient',
        
        where: filter.patient ? {
          [Op.or]: [
            { id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.inpatient_rooms,
        as: 'room',
        
        where: filter.room ? {
          [Op.or]: [
            { id: { [Op.in]: filter.room.split('|').map(term => Utils.uuid(term)) } },
            {
              room_number: {
                [Op.or]: filter.room.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.nursing_staff,
        as: 'supervising_nurse',
        
        where: filter.supervising_nurse ? {
          [Op.or]: [
            { id: { [Op.in]: filter.supervising_nurse.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.supervising_nurse.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.doctors,
        as: 'supervising_doctor',
        
        where: filter.supervising_doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.supervising_doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.supervising_doctor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.booking_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'room_bookings',
                        'booking_number',
                        filter.booking_number,
                    ),
                };
            }
            

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

            
            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.daysRange) {
                const [start, end] = filter.daysRange;

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_price: {
                    ...where.total_price,
                            [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.room_bookings.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(
                        'room_bookings',
                        'booking_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

