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

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

        const surgery_cases = await db.surgery_cases.create(
            {
                id: data.id || undefined,
        
        case_number: data.case_number
        ||
        null
            ,
            
        scheduled_start: data.scheduled_start
        ||
        null
            ,
            
        scheduled_end: data.scheduled_end
        ||
        null
            ,
            
        surgical_details: data.surgical_details
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await surgery_cases.setPatient( data.patient || null, {
            transaction,
        });
        
        await surgery_cases.setSurgeon( data.surgeon || null, {
            transaction,
        });
        

        
        await surgery_cases.setConsumables(data.consumables || [], {
            transaction,
        });
        

        

        return surgery_cases;
    }
    

    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 surgery_casesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                case_number: item.case_number
            ||
            null
            ,
            
                scheduled_start: item.scheduled_start
            ||
            null
            ,
            
                scheduled_end: item.scheduled_end
            ||
            null
            ,
            
                surgical_details: item.surgical_details
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return surgery_cases;
    }

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

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


        

        const updatePayload = {};
        
        if (data.case_number !== undefined) updatePayload.case_number = data.case_number;
        
        
        if (data.scheduled_start !== undefined) updatePayload.scheduled_start = data.scheduled_start;
        
        
        if (data.scheduled_end !== undefined) updatePayload.scheduled_end = data.scheduled_end;
        
        
        if (data.surgical_details !== undefined) updatePayload.surgical_details = data.surgical_details;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await surgery_cases.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.surgeon !== undefined) {
            await surgery_cases.setSurgeon(
              
              data.surgeon,
              
              { transaction }
            );
        }
        

        
        
        if (data.consumables !== undefined) {
            await surgery_cases.setConsumables(data.consumables, { transaction });
        }
        

        

        return surgery_cases;
    }

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

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

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


        return surgery_cases;
    }

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

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

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

        await surgery_cases.destroy({
            transaction
        });

        return surgery_cases;
    }

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

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

        if (!surgery_cases) {
            return surgery_cases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.surgery_consumables_surgery_case = await surgery_cases.getSurgery_consumables_surgery_case({
            transaction
        });
        
        
        output.anesthesia_records_surgery_case = await surgery_cases.getAnesthesia_records_surgery_case({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await surgery_cases.getPatient({
            transaction
        });
        
        
        output.surgeon = await surgery_cases.getSurgeon({
            transaction
        });
        
        
        output.consumables = await surgery_cases.getConsumables({
            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.doctors,
        as: 'surgeon',
        
        where: filter.surgeon ? {
          [Op.or]: [
            { id: { [Op.in]: filter.surgeon.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.surgeon.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.surgery_consumables,
        as: 'consumables',
        required: false,
      },


    ];

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

            
            if (filter.case_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'surgery_cases',
                        'case_number',
                        filter.case_number,
                    ),
                };
            }
            
            if (filter.surgical_details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'surgery_cases',
                        'surgical_details',
                        filter.surgical_details,
                    ),
                };
            }
            

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    scheduled_end: {
                    ...where.scheduled_end,
                            [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.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      


      if (filter.consumables) {
        const searchTerms = filter.consumables.split('|');

        include = [
          {
            model: db.surgery_consumables,
            as: 'consumables_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

