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

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

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

        
        await ct_studies.setOrder( data.order || null, {
            transaction,
        });
        
        await ct_studies.setCt_type( data.ct_type || null, {
            transaction,
        });
        

        

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

        return ct_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 ct_studiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                ct_number: item.ct_number
            ||
            null
            ,
            
                result_text: item.result_text
            ||
            null
            ,
            
                status: item.status
            ||
            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 ct_studies = await db.ct_studies.bulkCreate(ct_studiesData, { transaction });

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

        return ct_studies;
    }

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

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


        

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

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

        
        
        if (data.order !== undefined) {
            await ct_studies.setOrder(
              
              data.order,
              
              { transaction }
            );
        }
        
        if (data.ct_type !== undefined) {
            await ct_studies.setCt_type(
              
              data.ct_type,
              
              { transaction }
            );
        }
        

        
        

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

        return ct_studies;
    }

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

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

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


        return ct_studies;
    }

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

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

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

        await ct_studies.destroy({
            transaction
        });

        return ct_studies;
    }

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

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

        if (!ct_studies) {
            return ct_studies;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.order = await ct_studies.getOrder({
            transaction
        });
        
        
        output.ct_type = await ct_studies.getCt_type({
            transaction
        });
        
        
        output.result_files = await ct_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.ct_types,
        as: 'ct_type',
        
        where: filter.ct_type ? {
          [Op.or]: [
            { id: { [Op.in]: filter.ct_type.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.ct_type.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.ct_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ct_studies',
                        'ct_number',
                        filter.ct_number,
                    ),
                };
            }
            
            if (filter.result_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ct_studies',
                        'result_text',
                        filter.result_text,
                    ),
                };
            }
            

            
            

            
            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.ct_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(
                        'ct_studies',
                        'ct_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

