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

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

        const authorization_cases = await db.authorization_cases.create(
            {
                id: data.id || undefined,
        
        stage: data.stage
        ||
        null
            ,
            
        urgency: data.urgency
        ||
        null
            ,
            
        ordering_provider_name: data.ordering_provider_name
        ||
        null
            ,
            
        rendering_provider_name: data.rendering_provider_name
        ||
        null
            ,
            
        site_of_service: data.site_of_service
        ||
        null
            ,
            
        scheduled_date: data.scheduled_date
        ||
        null
            ,
            
        dollars_at_risk: data.dollars_at_risk
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        sla_state: data.sla_state
        ||
        null
            ,
            
        internal_notes: data.internal_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await authorization_cases.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await authorization_cases.setLocation( data.location || null, {
            transaction,
        });
        
        await authorization_cases.setPatient( data.patient || null, {
            transaction,
        });
        
        await authorization_cases.setPayer_plan( data.payer_plan || null, {
            transaction,
        });
        
        await authorization_cases.setCpt_code( data.cpt_code || null, {
            transaction,
        });
        
        await authorization_cases.setProcedure_family( data.procedure_family || null, {
            transaction,
        });
        
        await authorization_cases.setOwner_user( data.owner_user || null, {
            transaction,
        });
        

        

        

        return authorization_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 authorization_casesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                stage: item.stage
            ||
            null
            ,
            
                urgency: item.urgency
            ||
            null
            ,
            
                ordering_provider_name: item.ordering_provider_name
            ||
            null
            ,
            
                rendering_provider_name: item.rendering_provider_name
            ||
            null
            ,
            
                site_of_service: item.site_of_service
            ||
            null
            ,
            
                scheduled_date: item.scheduled_date
            ||
            null
            ,
            
                dollars_at_risk: item.dollars_at_risk
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                sla_state: item.sla_state
            ||
            null
            ,
            
                internal_notes: item.internal_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return authorization_cases;
    }

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

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


        

        const updatePayload = {};
        
        if (data.stage !== undefined) updatePayload.stage = data.stage;
        
        
        if (data.urgency !== undefined) updatePayload.urgency = data.urgency;
        
        
        if (data.ordering_provider_name !== undefined) updatePayload.ordering_provider_name = data.ordering_provider_name;
        
        
        if (data.rendering_provider_name !== undefined) updatePayload.rendering_provider_name = data.rendering_provider_name;
        
        
        if (data.site_of_service !== undefined) updatePayload.site_of_service = data.site_of_service;
        
        
        if (data.scheduled_date !== undefined) updatePayload.scheduled_date = data.scheduled_date;
        
        
        if (data.dollars_at_risk !== undefined) updatePayload.dollars_at_risk = data.dollars_at_risk;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.sla_state !== undefined) updatePayload.sla_state = data.sla_state;
        
        
        if (data.internal_notes !== undefined) updatePayload.internal_notes = data.internal_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await authorization_cases.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await authorization_cases.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.patient !== undefined) {
            await authorization_cases.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.payer_plan !== undefined) {
            await authorization_cases.setPayer_plan(
              
              data.payer_plan,
              
              { transaction }
            );
        }
        
        if (data.cpt_code !== undefined) {
            await authorization_cases.setCpt_code(
              
              data.cpt_code,
              
              { transaction }
            );
        }
        
        if (data.procedure_family !== undefined) {
            await authorization_cases.setProcedure_family(
              
              data.procedure_family,
              
              { transaction }
            );
        }
        
        if (data.owner_user !== undefined) {
            await authorization_cases.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        

        
        

        

        return authorization_cases;
    }

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

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

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


        return authorization_cases;
    }

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

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

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

        await authorization_cases.destroy({
            transaction
        });

        return authorization_cases;
    }

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

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

        if (!authorization_cases) {
            return authorization_cases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.case_documents_authorization_case = await authorization_cases.getCase_documents_authorization_case({
            transaction
        });
        
        
        output.submissions_authorization_case = await authorization_cases.getSubmissions_authorization_case({
            transaction
        });
        
        
        
        output.tasks_authorization_case = await authorization_cases.getTasks_authorization_case({
            transaction
        });
        
        
        output.denials_authorization_case = await authorization_cases.getDenials_authorization_case({
            transaction
        });
        
        
        
        
        
        
        output.ai_jobs_authorization_case = await authorization_cases.getAi_jobs_authorization_case({
            transaction
        });
        
        
        
        output.review_actions_authorization_case = await authorization_cases.getReview_actions_authorization_case({
            transaction
        });
        
        
        
        
        
        
        output.organization = await authorization_cases.getOrganization({
            transaction
        });
        
        
        output.location = await authorization_cases.getLocation({
            transaction
        });
        
        
        output.patient = await authorization_cases.getPatient({
            transaction
        });
        
        
        output.payer_plan = await authorization_cases.getPayer_plan({
            transaction
        });
        
        
        output.cpt_code = await authorization_cases.getCpt_code({
            transaction
        });
        
        
        output.procedure_family = await authorization_cases.getProcedure_family({
            transaction
        });
        
        
        output.owner_user = await authorization_cases.getOwner_user({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.organizations,
        as: 'organization',
        
      },

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

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

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

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

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

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



    ];

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

            
            if (filter.ordering_provider_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'authorization_cases',
                        'ordering_provider_name',
                        filter.ordering_provider_name,
                    ),
                };
            }
            
            if (filter.rendering_provider_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'authorization_cases',
                        'rendering_provider_name',
                        filter.rendering_provider_name,
                    ),
                };
            }
            
            if (filter.site_of_service) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'authorization_cases',
                        'site_of_service',
                        filter.site_of_service,
                    ),
                };
            }
            
            if (filter.internal_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'authorization_cases',
                        'internal_notes',
                        filter.internal_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.stage) {
                where = {
                    ...where,
                stage: filter.stage,
            };
            }
            
            if (filter.urgency) {
                where = {
                    ...where,
                urgency: filter.urgency,
            };
            }
            
            if (filter.sla_state) {
                where = {
                    ...where,
                sla_state: filter.sla_state,
            };
            }
            


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[Op.or]: listItems}
        };
      }
      

      

      

      

      

      

      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.authorization_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'authorization_cases',
                        'site_of_service',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

