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

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

        const tenants = await db.tenants.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        plan_tier: data.plan_tier
        ||
        null
            ,
            
        tenant_status: data.tenant_status
        ||
        null
            ,
            
        activated_at: data.activated_at
        ||
        null
            ,
            
        suspended_at: data.suspended_at
        ||
        null
            ,
            
        default_region: data.default_region
        ||
        null
            ,
            
        e2ee_default_enabled: data.e2ee_default_enabled
        ||
        false
        
            ,
            
        education_module_enabled: data.education_module_enabled
        ||
        false
        
            ,
            
        marketplace_enabled: data.marketplace_enabled
        ||
        false
        
            ,
            
        data_retention_policy: data.data_retention_policy
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tenants.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return tenants;
    }
    

    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 tenantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                plan_tier: item.plan_tier
            ||
            null
            ,
            
                tenant_status: item.tenant_status
            ||
            null
            ,
            
                activated_at: item.activated_at
            ||
            null
            ,
            
                suspended_at: item.suspended_at
            ||
            null
            ,
            
                default_region: item.default_region
            ||
            null
            ,
            
                e2ee_default_enabled: item.e2ee_default_enabled
            ||
            false
        
            ,
            
                education_module_enabled: item.education_module_enabled
            ||
            false
        
            ,
            
                marketplace_enabled: item.marketplace_enabled
            ||
            false
        
            ,
            
                data_retention_policy: item.data_retention_policy
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return tenants;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.plan_tier !== undefined) updatePayload.plan_tier = data.plan_tier;
        
        
        if (data.tenant_status !== undefined) updatePayload.tenant_status = data.tenant_status;
        
        
        if (data.activated_at !== undefined) updatePayload.activated_at = data.activated_at;
        
        
        if (data.suspended_at !== undefined) updatePayload.suspended_at = data.suspended_at;
        
        
        if (data.default_region !== undefined) updatePayload.default_region = data.default_region;
        
        
        if (data.e2ee_default_enabled !== undefined) updatePayload.e2ee_default_enabled = data.e2ee_default_enabled;
        
        
        if (data.education_module_enabled !== undefined) updatePayload.education_module_enabled = data.education_module_enabled;
        
        
        if (data.marketplace_enabled !== undefined) updatePayload.marketplace_enabled = data.marketplace_enabled;
        
        
        if (data.data_retention_policy !== undefined) updatePayload.data_retention_policy = data.data_retention_policy;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return tenants;
    }

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

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

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


        return tenants;
    }

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

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

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

        await tenants.destroy({
            transaction
        });

        return tenants;
    }

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

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

        if (!tenants) {
            return tenants;
        }

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

        
        
        
        
        
        
        
        
        
        output.identity_providers_tenant = await tenants.getIdentity_providers_tenant({
            transaction
        });
        
        
        
        output.policy_rules_tenant = await tenants.getPolicy_rules_tenant({
            transaction
        });
        
        
        output.kms_configs_tenant = await tenants.getKms_configs_tenant({
            transaction
        });
        
        
        output.conference_templates_tenant = await tenants.getConference_templates_tenant({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.files_tenant = await tenants.getFiles_tenant({
            transaction
        });
        
        
        
        
        
        
        
        output.layout_models_tenant = await tenants.getLayout_models_tenant({
            transaction
        });
        
        
        
        
        
        
        output.external_integrations_tenant = await tenants.getExternal_integrations_tenant({
            transaction
        });
        
        
        
        output.courses_tenant = await tenants.getCourses_tenant({
            transaction
        });
        
        
        
        
        
        
        
        output.marketplace_apps_tenant = await tenants.getMarketplace_apps_tenant({
            transaction
        });
        
        
        
        
        output.audit_events_tenant = await tenants.getAudit_events_tenant({
            transaction
        });
        
        
        output.data_subject_requests_tenant = await tenants.getData_subject_requests_tenant({
            transaction
        });
        
        
        
        
        output.feature_flags_tenant = await tenants.getFeature_flags_tenant({
            transaction
        });
        
        
        
        output.event_streams_tenant = await tenants.getEvent_streams_tenant({
            transaction
        });
        
        
        
        
        output.organizations = await tenants.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.default_region) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'default_region',
                        filter.default_region,
                    ),
                };
            }
            
            if (filter.data_retention_policy) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'data_retention_policy',
                        filter.data_retention_policy,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.plan_tier) {
                where = {
                    ...where,
                plan_tier: filter.plan_tier,
            };
            }
            
            if (filter.tenant_status) {
                where = {
                    ...where,
                tenant_status: filter.tenant_status,
            };
            }
            
            if (filter.e2ee_default_enabled) {
                where = {
                    ...where,
                e2ee_default_enabled: filter.e2ee_default_enabled,
            };
            }
            
            if (filter.education_module_enabled) {
                where = {
                    ...where,
                education_module_enabled: filter.education_module_enabled,
            };
            }
            
            if (filter.marketplace_enabled) {
                where = {
                    ...where,
                marketplace_enabled: filter.marketplace_enabled,
            };
            }
            


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

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

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

    
};

