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

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

        const sti_tests = await db.sti_tests.create(
            {
                id: data.id || undefined,
        
        tested_at: data.tested_at
        ||
        null
            ,
            
        tests_performed: data.tests_performed
        ||
        null
            ,
            
        result_status: data.result_status
        ||
        null
            ,
            
        results_notes: data.results_notes
        ||
        null
            ,
            
        next_recommended_test_date: data.next_recommended_test_date
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sti_tests.setUser( data.user || null, {
            transaction,
        });
        
        await sti_tests.setClinic_provider( data.clinic_provider || null, {
            transaction,
        });
        

        

        

        return sti_tests;
    }
    

    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 sti_testsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                tested_at: item.tested_at
            ||
            null
            ,
            
                tests_performed: item.tests_performed
            ||
            null
            ,
            
                result_status: item.result_status
            ||
            null
            ,
            
                results_notes: item.results_notes
            ||
            null
            ,
            
                next_recommended_test_date: item.next_recommended_test_date
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return sti_tests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.tested_at !== undefined) updatePayload.tested_at = data.tested_at;
        
        
        if (data.tests_performed !== undefined) updatePayload.tests_performed = data.tests_performed;
        
        
        if (data.result_status !== undefined) updatePayload.result_status = data.result_status;
        
        
        if (data.results_notes !== undefined) updatePayload.results_notes = data.results_notes;
        
        
        if (data.next_recommended_test_date !== undefined) updatePayload.next_recommended_test_date = data.next_recommended_test_date;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await sti_tests.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.clinic_provider !== undefined) {
            await sti_tests.setClinic_provider(
              
              data.clinic_provider,
              
              { transaction }
            );
        }
        

        
        

        

        return sti_tests;
    }

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

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

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


        return sti_tests;
    }

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

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

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

        await sti_tests.destroy({
            transaction
        });

        return sti_tests;
    }

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

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

        if (!sti_tests) {
            return sti_tests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await sti_tests.getUser({
            transaction
        });
        
        
        output.clinic_provider = await sti_tests.getClinic_provider({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.tests_performed) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sti_tests',
                        'tests_performed',
                        filter.tests_performed,
                    ),
                };
            }
            
            if (filter.results_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sti_tests',
                        'results_notes',
                        filter.results_notes,
                    ),
                };
            }
            

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    next_recommended_test_date: {
                    ...where.next_recommended_test_date,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.result_status) {
                where = {
                    ...where,
                result_status: filter.result_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.sti_tests.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(
                        'sti_tests',
                        'tests_performed',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

