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

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

        const denials = await db.denials.create(
            {
                id: data.id || undefined,
        
        denial_at: data.denial_at
        ||
        null
            ,
            
        denial_type: data.denial_type
        ||
        null
            ,
            
        denial_reason_text: data.denial_reason_text
        ||
        null
            ,
            
        denial_code: data.denial_code
        ||
        null
            ,
            
        dollars_denied: data.dollars_denied
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await denials.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await denials.setLocation( data.location || null, {
            transaction,
        });
        
        await denials.setAuthorization_case( data.authorization_case || null, {
            transaction,
        });
        
        await denials.setSubmission( data.submission || null, {
            transaction,
        });
        
        await denials.setOwner_user( data.owner_user || null, {
            transaction,
        });
        

        

        

        return denials;
    }
    

    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 denialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                denial_at: item.denial_at
            ||
            null
            ,
            
                denial_type: item.denial_type
            ||
            null
            ,
            
                denial_reason_text: item.denial_reason_text
            ||
            null
            ,
            
                denial_code: item.denial_code
            ||
            null
            ,
            
                dollars_denied: item.dollars_denied
            ||
            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 denials = await db.denials.bulkCreate(denialsData, { transaction });

        // For each item created, replace relation files
        

        return denials;
    }

    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 denials = await db.denials.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.denial_at !== undefined) updatePayload.denial_at = data.denial_at;
        
        
        if (data.denial_type !== undefined) updatePayload.denial_type = data.denial_type;
        
        
        if (data.denial_reason_text !== undefined) updatePayload.denial_reason_text = data.denial_reason_text;
        
        
        if (data.denial_code !== undefined) updatePayload.denial_code = data.denial_code;
        
        
        if (data.dollars_denied !== undefined) updatePayload.dollars_denied = data.dollars_denied;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await denials.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await denials.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.authorization_case !== undefined) {
            await denials.setAuthorization_case(
              
              data.authorization_case,
              
              { transaction }
            );
        }
        
        if (data.submission !== undefined) {
            await denials.setSubmission(
              
              data.submission,
              
              { transaction }
            );
        }
        
        if (data.owner_user !== undefined) {
            await denials.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        

        
        

        

        return denials;
    }

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

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

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


        return denials;
    }

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

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

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

        await denials.destroy({
            transaction
        });

        return denials;
    }

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

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

        if (!denials) {
            return denials;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.appeals_denial = await denials.getAppeals_denial({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await denials.getOrganization({
            transaction
        });
        
        
        output.location = await denials.getLocation({
            transaction
        });
        
        
        output.authorization_case = await denials.getAuthorization_case({
            transaction
        });
        
        
        output.submission = await denials.getSubmission({
            transaction
        });
        
        
        output.owner_user = await denials.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.authorization_cases,
        as: 'authorization_case',
        
        where: filter.authorization_case ? {
          [Op.or]: [
            { id: { [Op.in]: filter.authorization_case.split('|').map(term => Utils.uuid(term)) } },
            {
              site_of_service: {
                [Op.or]: filter.authorization_case.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.submissions,
        as: 'submission',
        
        where: filter.submission ? {
          [Op.or]: [
            { id: { [Op.in]: filter.submission.split('|').map(term => Utils.uuid(term)) } },
            {
              reference_number: {
                [Op.or]: filter.submission.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.denial_reason_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'denials',
                        'denial_reason_text',
                        filter.denial_reason_text,
                    ),
                };
            }
            
            if (filter.denial_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'denials',
                        'denial_code',
                        filter.denial_code,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.denial_type) {
                where = {
                    ...where,
                denial_type: filter.denial_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


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

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

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

    
};

