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

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

        const rule_requirements = await db.rule_requirements.create(
            {
                id: data.id || undefined,
        
        requirement_type: data.requirement_type
        ||
        null
            ,
            
        requirement_label: data.requirement_label
        ||
        null
            ,
            
        evidence_needed: data.evidence_needed
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await rule_requirements.setPayer_rule( data.payer_rule || null, {
            transaction,
        });
        
        await rule_requirements.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return rule_requirements;
    }
    

    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 rule_requirementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                requirement_type: item.requirement_type
            ||
            null
            ,
            
                requirement_label: item.requirement_label
            ||
            null
            ,
            
                evidence_needed: item.evidence_needed
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return rule_requirements;
    }

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


        

        const updatePayload = {};
        
        if (data.requirement_type !== undefined) updatePayload.requirement_type = data.requirement_type;
        
        
        if (data.requirement_label !== undefined) updatePayload.requirement_label = data.requirement_label;
        
        
        if (data.evidence_needed !== undefined) updatePayload.evidence_needed = data.evidence_needed;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.payer_rule !== undefined) {
            await rule_requirements.setPayer_rule(
              
              data.payer_rule,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await rule_requirements.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return rule_requirements;
    }

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

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

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


        return rule_requirements;
    }

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

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

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

        await rule_requirements.destroy({
            transaction
        });

        return rule_requirements;
    }

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

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

        if (!rule_requirements) {
            return rule_requirements;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payer_rule = await rule_requirements.getPayer_rule({
            transaction
        });
        
        
        output.organizations = await rule_requirements.getOrganizations({
            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.payer_rules,
        as: 'payer_rule',
        
        where: filter.payer_rule ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payer_rule.split('|').map(term => Utils.uuid(term)) } },
            {
              version_label: {
                [Op.or]: filter.payer_rule.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.requirement_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rule_requirements',
                        'requirement_label',
                        filter.requirement_label,
                    ),
                };
            }
            
            if (filter.evidence_needed) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rule_requirements',
                        'evidence_needed',
                        filter.evidence_needed,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.requirement_type) {
                where = {
                    ...where,
                requirement_type: filter.requirement_type,
            };
            }
            
            if (filter.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            


      

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

        where = {
          ...where,
          organizationsId: {[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.rule_requirements.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(
                        'rule_requirements',
                        'requirement_label',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

