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

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

        const anesthesia_records = await db.anesthesia_records.create(
            {
                id: data.id || undefined,
        
        medications: data.medications
        ||
        null
            ,
            
        start_time: data.start_time
        ||
        null
            ,
            
        end_time: data.end_time
        ||
        null
            ,
            
        recovery_notes: data.recovery_notes
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await anesthesia_records.setSurgery_case( data.surgery_case || null, {
            transaction,
        });
        

        

        

        return anesthesia_records;
    }
    

    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 anesthesia_recordsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                medications: item.medications
            ||
            null
            ,
            
                start_time: item.start_time
            ||
            null
            ,
            
                end_time: item.end_time
            ||
            null
            ,
            
                recovery_notes: item.recovery_notes
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return anesthesia_records;
    }

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

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


        

        const updatePayload = {};
        
        if (data.medications !== undefined) updatePayload.medications = data.medications;
        
        
        if (data.start_time !== undefined) updatePayload.start_time = data.start_time;
        
        
        if (data.end_time !== undefined) updatePayload.end_time = data.end_time;
        
        
        if (data.recovery_notes !== undefined) updatePayload.recovery_notes = data.recovery_notes;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.surgery_case !== undefined) {
            await anesthesia_records.setSurgery_case(
              
              data.surgery_case,
              
              { transaction }
            );
        }
        

        
        

        

        return anesthesia_records;
    }

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

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

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


        return anesthesia_records;
    }

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

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

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

        await anesthesia_records.destroy({
            transaction
        });

        return anesthesia_records;
    }

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

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

        if (!anesthesia_records) {
            return anesthesia_records;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.surgery_case = await anesthesia_records.getSurgery_case({
            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.surgery_cases,
        as: 'surgery_case',
        
        where: filter.surgery_case ? {
          [Op.or]: [
            { id: { [Op.in]: filter.surgery_case.split('|').map(term => Utils.uuid(term)) } },
            {
              case_number: {
                [Op.or]: filter.surgery_case.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.medications) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'anesthesia_records',
                        'medications',
                        filter.medications,
                    ),
                };
            }
            
            if (filter.recovery_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'anesthesia_records',
                        'recovery_notes',
                        filter.recovery_notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    price: {
                    ...where.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.anesthesia_records.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(
                        'anesthesia_records',
                        'recovery_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

