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

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

        const radiology_studies = await db.radiology_studies.create(
            {
                id: data.id || undefined,
        
        study_number: data.study_number
        ||
        null
            ,
            
        report_summary: data.report_summary
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await radiology_studies.setOrder( data.order || null, {
            transaction,
        });
        
        await radiology_studies.setStudy_type( data.study_type || null, {
            transaction,
        });
        
        await radiology_studies.setTechnician( data.technician || null, {
            transaction,
        });
        

        

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

        return radiology_studies;
    }
    

    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 radiology_studiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                study_number: item.study_number
            ||
            null
            ,
            
                report_summary: item.report_summary
            ||
            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 radiology_studies = await db.radiology_studies.bulkCreate(radiology_studiesData, { transaction });

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

        return radiology_studies;
    }

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

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


        

        const updatePayload = {};
        
        if (data.study_number !== undefined) updatePayload.study_number = data.study_number;
        
        
        if (data.report_summary !== undefined) updatePayload.report_summary = data.report_summary;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.order !== undefined) {
            await radiology_studies.setOrder(
              
              data.order,
              
              { transaction }
            );
        }
        
        if (data.study_type !== undefined) {
            await radiology_studies.setStudy_type(
              
              data.study_type,
              
              { transaction }
            );
        }
        
        if (data.technician !== undefined) {
            await radiology_studies.setTechnician(
              
              data.technician,
              
              { transaction }
            );
        }
        

        
        

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

        return radiology_studies;
    }

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

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

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


        return radiology_studies;
    }

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

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

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

        await radiology_studies.destroy({
            transaction
        });

        return radiology_studies;
    }

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

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

        if (!radiology_studies) {
            return radiology_studies;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.order = await radiology_studies.getOrder({
            transaction
        });
        
        
        output.study_type = await radiology_studies.getStudy_type({
            transaction
        });
        
        
        output.technician = await radiology_studies.getTechnician({
            transaction
        });
        
        
        output.result_files = await radiology_studies.getResult_files({
            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.orders,
        as: 'order',
        
        where: filter.order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.study_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'radiology_studies',
                        'study_number',
                        filter.study_number,
                    ),
                };
            }
            
            if (filter.report_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'radiology_studies',
                        'report_summary',
                        filter.report_summary,
                    ),
                };
            }
            

            
            

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

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

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

    
};

