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

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

        const cathlab_cases = await db.cathlab_cases.create(
            {
                id: data.id || undefined,
        
        case_number: data.case_number
        ||
        null
            ,
            
        procedure_details: data.procedure_details
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        scheduled_date: data.scheduled_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cathlab_cases.setPatient( data.patient || null, {
            transaction,
        });
        
        await cathlab_cases.setDoctor( data.doctor || null, {
            transaction,
        });
        

        

        

        return cathlab_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 cathlab_casesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                case_number: item.case_number
            ||
            null
            ,
            
                procedure_details: item.procedure_details
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                scheduled_date: item.scheduled_date
            ||
            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 cathlab_cases = await db.cathlab_cases.bulkCreate(cathlab_casesData, { transaction });

        // For each item created, replace relation files
        

        return cathlab_cases;
    }

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

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


        

        const updatePayload = {};
        
        if (data.case_number !== undefined) updatePayload.case_number = data.case_number;
        
        
        if (data.procedure_details !== undefined) updatePayload.procedure_details = data.procedure_details;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.scheduled_date !== undefined) updatePayload.scheduled_date = data.scheduled_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await cathlab_cases.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.doctor !== undefined) {
            await cathlab_cases.setDoctor(
              
              data.doctor,
              
              { transaction }
            );
        }
        

        
        

        

        return cathlab_cases;
    }

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

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

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


        return cathlab_cases;
    }

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

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

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

        await cathlab_cases.destroy({
            transaction
        });

        return cathlab_cases;
    }

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

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

        if (!cathlab_cases) {
            return cathlab_cases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await cathlab_cases.getPatient({
            transaction
        });
        
        
        output.doctor = await cathlab_cases.getDoctor({
            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: 'doctor',
        
        where: filter.doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.doctor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

        const records = await db.cathlab_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,
        }));
    }

    
};

