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

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

        const compliance_rule_overrides = await db.compliance_rule_overrides.create(
            {
                id: data.id || undefined,
        
        override_title: data.override_title
        ||
        null
            ,
            
        frequency: data.frequency
        ||
        null
            ,
            
        due_day_of_month: data.due_day_of_month
        ||
        null
            ,
            
        due_month_of_year: data.due_month_of_year
        ||
        null
            ,
            
        grace_days: data.grace_days
        ||
        null
            ,
            
        risk_level: data.risk_level
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        reason: data.reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await compliance_rule_overrides.setCompany( data.company || null, {
            transaction,
        });
        
        await compliance_rule_overrides.setTemplate( data.template || null, {
            transaction,
        });
        
        await compliance_rule_overrides.setBranch( data.branch || null, {
            transaction,
        });
        
        await compliance_rule_overrides.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return compliance_rule_overrides;
    }
    

    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 compliance_rule_overridesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                override_title: item.override_title
            ||
            null
            ,
            
                frequency: item.frequency
            ||
            null
            ,
            
                due_day_of_month: item.due_day_of_month
            ||
            null
            ,
            
                due_month_of_year: item.due_month_of_year
            ||
            null
            ,
            
                grace_days: item.grace_days
            ||
            null
            ,
            
                risk_level: item.risk_level
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                reason: item.reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return compliance_rule_overrides;
    }

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


        

        const updatePayload = {};
        
        if (data.override_title !== undefined) updatePayload.override_title = data.override_title;
        
        
        if (data.frequency !== undefined) updatePayload.frequency = data.frequency;
        
        
        if (data.due_day_of_month !== undefined) updatePayload.due_day_of_month = data.due_day_of_month;
        
        
        if (data.due_month_of_year !== undefined) updatePayload.due_month_of_year = data.due_month_of_year;
        
        
        if (data.grace_days !== undefined) updatePayload.grace_days = data.grace_days;
        
        
        if (data.risk_level !== undefined) updatePayload.risk_level = data.risk_level;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await compliance_rule_overrides.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.template !== undefined) {
            await compliance_rule_overrides.setTemplate(
              
              data.template,
              
              { transaction }
            );
        }
        
        if (data.branch !== undefined) {
            await compliance_rule_overrides.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await compliance_rule_overrides.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return compliance_rule_overrides;
    }

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

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

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


        return compliance_rule_overrides;
    }

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

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

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

        await compliance_rule_overrides.destroy({
            transaction
        });

        return compliance_rule_overrides;
    }

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

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

        if (!compliance_rule_overrides) {
            return compliance_rule_overrides;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await compliance_rule_overrides.getCompany({
            transaction
        });
        
        
        output.template = await compliance_rule_overrides.getTemplate({
            transaction
        });
        
        
        output.branch = await compliance_rule_overrides.getBranch({
            transaction
        });
        
        
        output.organizations = await compliance_rule_overrides.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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              company_name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.branches,
        as: 'branch',
        
        where: filter.branch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.branch.split('|').map(term => Utils.uuid(term)) } },
            {
              branch_name: {
                [Op.or]: filter.branch.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.override_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'compliance_rule_overrides',
                        'override_title',
                        filter.override_title,
                    ),
                };
            }
            
            if (filter.reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'compliance_rule_overrides',
                        'reason',
                        filter.reason,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.frequency) {
                where = {
                    ...where,
                frequency: filter.frequency,
            };
            }
            
            if (filter.risk_level) {
                where = {
                    ...where,
                risk_level: filter.risk_level,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_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.compliance_rule_overrides.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(
                        'compliance_rule_overrides',
                        'override_title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

