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

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

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

        
        await endoscopy_cases.setVisit( data.visit || null, {
            transaction,
        });
        
        await endoscopy_cases.setDoctor( data.doctor || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.endoscopy_cases.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: endoscopy_cases.id,
            },
            data.attachments,
            options,
        );
        

        return endoscopy_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 endoscopy_casesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                case_number: item.case_number
            ||
            null
            ,
            
                diagnosis: item.diagnosis
            ||
            null
            ,
            
                procedure_details: item.procedure_details
            ||
            null
            ,
            
                recommendations: item.recommendations
            ||
            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 endoscopy_cases = await db.endoscopy_cases.bulkCreate(endoscopy_casesData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < endoscopy_cases.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.endoscopy_cases.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: endoscopy_cases[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return endoscopy_cases;
    }

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

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


        

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

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

        
        
        if (data.visit !== undefined) {
            await endoscopy_cases.setVisit(
              
              data.visit,
              
              { transaction }
            );
        }
        
        if (data.doctor !== undefined) {
            await endoscopy_cases.setDoctor(
              
              data.doctor,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.endoscopy_cases.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: endoscopy_cases.id,
            },
            data.attachments,
            options,
        );
        

        return endoscopy_cases;
    }

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

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

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


        return endoscopy_cases;
    }

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

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

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

        await endoscopy_cases.destroy({
            transaction
        });

        return endoscopy_cases;
    }

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

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

        if (!endoscopy_cases) {
            return endoscopy_cases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.visit = await endoscopy_cases.getVisit({
            transaction
        });
        
        
        output.doctor = await endoscopy_cases.getDoctor({
            transaction
        });
        
        
        output.attachments = await endoscopy_cases.getAttachments({
            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.visits,
        as: 'visit',
        
        where: filter.visit ? {
          [Op.or]: [
            { id: { [Op.in]: filter.visit.split('|').map(term => Utils.uuid(term)) } },
            {
              visit_number: {
                [Op.or]: filter.visit.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}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

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

            
            

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

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

    
};

