
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const TenantAccess = require('./tenantAccess');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Organization_settingsDBApi {
    

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

        const organization_settings = await db.organization_settings.create(
            {
                id: data.id || undefined,
        
        default_retention_period: data.default_retention_period
        ||
        null
            ,
            
        require_mfa_for_all_users: data.require_mfa_for_all_users
        ||
        false
        
            ,
            
        enable_global_search: data.enable_global_search
        ||
        false
        
            ,
            
        enable_control_framework_library: data.enable_control_framework_library
        ||
        false
        
            ,
            
        date_format: data.date_format
        ||
        null
            ,
            
        branding_primary_color: data.branding_primary_color
        ||
        null
            ,
            
        notification_email_from_name: data.notification_email_from_name
        ||
        null
            ,
            
        notification_email_from_address: data.notification_email_from_address
        ||
        null
            ,
            
        slack_webhook_url: data.slack_webhook_url
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await organization_settings.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.organization_settings.getTableName(),
                belongsToColumn: 'branding_logo',
                belongsToId: organization_settings.id,
            },
            data.branding_logo,
            options,
        );
        

        return organization_settings;
    }
    

    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 organization_settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                default_retention_period: item.default_retention_period
            ||
            null
            ,
            
                require_mfa_for_all_users: item.require_mfa_for_all_users
            ||
            false
        
            ,
            
                enable_global_search: item.enable_global_search
            ||
            false
        
            ,
            
                enable_control_framework_library: item.enable_control_framework_library
            ||
            false
        
            ,
            
                date_format: item.date_format
            ||
            null
            ,
            
                branding_primary_color: item.branding_primary_color
            ||
            null
            ,
            
                notification_email_from_name: item.notification_email_from_name
            ||
            null
            ,
            
                notification_email_from_address: item.notification_email_from_address
            ||
            null
            ,
            
                slack_webhook_url: item.slack_webhook_url
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < organization_settings.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.organization_settings.getTableName(),
                    belongsToColumn: 'branding_logo',
                    belongsToId: organization_settings[i].id,
                },
                data[i].branding_logo,
                options,
            );
        }
        

        return organization_settings;
    }

    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 organization_settings = await TenantAccess.findByPkOrThrow(db.organization_settings, id, options);


        

        const updatePayload = {};
        
        if (data.default_retention_period !== undefined) updatePayload.default_retention_period = data.default_retention_period;
        
        
        if (data.require_mfa_for_all_users !== undefined) updatePayload.require_mfa_for_all_users = data.require_mfa_for_all_users;
        
        
        if (data.enable_global_search !== undefined) updatePayload.enable_global_search = data.enable_global_search;
        
        
        if (data.enable_control_framework_library !== undefined) updatePayload.enable_control_framework_library = data.enable_control_framework_library;
        
        
        if (data.date_format !== undefined) updatePayload.date_format = data.date_format;
        
        
        if (data.branding_primary_color !== undefined) updatePayload.branding_primary_color = data.branding_primary_color;
        
        
        if (data.notification_email_from_name !== undefined) updatePayload.notification_email_from_name = data.notification_email_from_name;
        
        
        if (data.notification_email_from_address !== undefined) updatePayload.notification_email_from_address = data.notification_email_from_address;
        
        
        if (data.slack_webhook_url !== undefined) updatePayload.slack_webhook_url = data.slack_webhook_url;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await organization_settings.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.organization_settings.getTableName(),
                belongsToColumn: 'branding_logo',
                belongsToId: organization_settings.id,
            },
            data.branding_logo,
            options,
        );
        

        return organization_settings;
    }

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

        const organization_settings = await TenantAccess.findAllByIds(db.organization_settings, ids, options);

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


        return organization_settings;
    }

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

        const organization_settings = await TenantAccess.findByPkOrThrow(db.organization_settings, id, options);

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

        await organization_settings.destroy({
            transaction
        });

        return organization_settings;
    }

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

        const organization_settings = await TenantAccess.findOne(db.organization_settings, where, options);

        if (!organization_settings) {
            return organization_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await organization_settings.getOrganization({
            transaction
        });
        
        
        output.branding_logo = await organization_settings.getBranding_logo({
            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.file,
        as: 'branding_logo',
      },

    ];

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

            
            if (filter.branding_primary_color) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'branding_primary_color',
                        filter.branding_primary_color,
                    ),
                };
            }
            
            if (filter.notification_email_from_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'notification_email_from_name',
                        filter.notification_email_from_name,
                    ),
                };
            }
            
            if (filter.notification_email_from_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'notification_email_from_address',
                        filter.notification_email_from_address,
                    ),
                };
            }
            
            if (filter.slack_webhook_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'organization_settings',
                        'slack_webhook_url',
                        filter.slack_webhook_url,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.default_retention_period) {
                where = {
                    ...where,
                default_retention_period: filter.default_retention_period,
            };
            }
            
            if (filter.require_mfa_for_all_users) {
                where = {
                    ...where,
                require_mfa_for_all_users: filter.require_mfa_for_all_users,
            };
            }
            
            if (filter.enable_global_search) {
                where = {
                    ...where,
                enable_global_search: filter.enable_global_search,
            };
            }
            
            if (filter.enable_control_framework_library) {
                where = {
                    ...where,
                enable_control_framework_library: filter.enable_control_framework_library,
            };
            }
            
            if (filter.date_format) {
                where = {
                    ...where,
                date_format: filter.date_format,
            };
            }
            


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

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

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

    
};

