import db from '@nangohq/database';
import { isCloud, nanoid } from '@nangohq/utils';
import { NangoError } from '../utils/error.js';
import encryptionManager from '../utils/encryption.manager.js';
import syncManager from './sync/manager.service.js';
import { deleteSyncFilesForConfig, deleteByConfigId as deleteSyncConfigByConfigId } from '../services/sync/config/config.service.js';
import environmentService from '../services/environment.service.js';
class ConfigService {
    async getById(id) {
        const result = await db.knex.select('*').from(`_nango_configs`).where({ id, deleted: false }).first();
        if (!result) {
            return null;
        }
        return encryptionManager.decryptProviderConfig(result);
    }
    async getProviderName(providerConfigKey) {
        const result = await db.knex.select('provider').from(`_nango_configs`).where({ unique_key: providerConfigKey, deleted: false });
        if (result == null || result.length == 0 || result[0] == null) {
            return null;
        }
        return result[0].provider;
    }
    async getIdByProviderConfigKey(environment_id, providerConfigKey) {
        const result = await db.knex
            .select('id')
            .from(`_nango_configs`)
            .where({ unique_key: providerConfigKey, environment_id, deleted: false });
        if (result == null || result.length == 0 || result[0] == null) {
            return null;
        }
        return result[0].id;
    }
    async getProviderConfigByUuid(providerConfigKey, environment_uuid) {
        if (!providerConfigKey) {
            throw new NangoError('missing_provider_config');
        }
        if (!environment_uuid) {
            throw new NangoError('missing_environment_uuid');
        }
        const environment_id = await environmentService.getIdByUuid(environment_uuid);
        if (!environment_id) {
            return null;
        }
        return this.getProviderConfig(providerConfigKey, environment_id);
    }
    async getProviderConfig(providerConfigKey, environment_id) {
        const result = await db.knex
            .select('*')
            .from(`_nango_configs`)
            .where({ unique_key: providerConfigKey, environment_id, deleted: false })
            .first();
        if (!result) {
            return null;
        }
        return encryptionManager.decryptProviderConfig(result);
    }
    async listProviderConfigs(environment_id) {
        return (await db.knex
            .select('*')
            .from(`_nango_configs`)
            .where({ environment_id, deleted: false })
            .orderBy('provider', 'asc')
            .orderBy('created_at', 'asc'))
            .map((config) => encryptionManager.decryptProviderConfig(config))
            .filter(Boolean);
    }
    async listIntegrationForApi(environment_id) {
        const connectionCountSubquery = db
            .knex('_nango_connections')
            .count('* as connection_count')
            .where({
            '_nango_connections.environment_id': db.knex.ref('_nango_configs.environment_id'),
            '_nango_connections.config_id': db.knex.ref('_nango_configs.id'),
            deleted: false
        })
            .as('connection_count');
        const res = await db.knex
            .select('*', connectionCountSubquery)
            .from(`_nango_configs`)
            .where({ environment_id, deleted: false })
            .orderBy('provider', 'asc')
            .orderBy('created_at', 'asc');
        return res;
    }
    async listProviderConfigsByProvider(environment_id, provider) {
        return (await db.knex.select('*').from(`_nango_configs`).where({ environment_id, provider, deleted: false }))
            .map((config) => encryptionManager.decryptProviderConfig(config))
            .filter((config) => config != null);
    }
    async createProviderConfig(config) {
        const configToInsert = config.oauth_client_secret ? encryptionManager.encryptProviderConfig(config) : config;
        const res = await db.knex.from(`_nango_configs`).insert(configToInsert).returning('*');
        return res[0] ?? null;
    }
    async createEmptyProviderConfig(provider, environment_id) {
        const exists = await db.knex
            .count('*')
            .from(`_nango_configs`)
            .where({ provider, environment_id, deleted: false })
            .first();
        const config = await this.createProviderConfig({
            environment_id,
            unique_key: exists?.count === '0' ? provider : `${provider}-${nanoid(4).toLocaleLowerCase()}`,
            provider
        });
        if (!config) {
            throw new NangoError('unknown_provider_config');
        }
        return config;
    }
    async deleteProviderConfig({ id, environmentId, providerConfigKey, orchestrator }) {
        await syncManager.deleteSyncsByProviderConfig(environmentId, providerConfigKey, orchestrator);
        if (isCloud) {
            await deleteSyncFilesForConfig(id, environmentId);
        }
        await deleteSyncConfigByConfigId(id);
        const updated = await db.knex.from(`_nango_configs`).where({ id, deleted: false }).update({ deleted: true, deleted_at: new Date() });
        if (updated <= 0) {
            return false;
        }
        await db.knex
            .from(`_nango_connections`)
            .where({ provider_config_key: providerConfigKey, environment_id: environmentId, deleted: false })
            .update({ deleted: true, deleted_at: new Date() });
        return true;
    }
    async editProviderConfig(config) {
        return db.knex
            .from(`_nango_configs`)
            .where({ id: config.id, environment_id: config.environment_id, deleted: false })
            .update(encryptionManager.encryptProviderConfig(config));
    }
    async editProviderConfigName(providerConfigKey, newUniqueKey, environment_id) {
        return db.knex
            .from(`_nango_configs`)
            .where({ unique_key: providerConfigKey, environment_id, deleted: false })
            .update({ unique_key: newUniqueKey });
    }
    async getConfigIdByProvider(provider, environment_id) {
        const result = await db.knex
            .select('id', 'unique_key')
            .from(`_nango_configs`)
            .where({ provider, environment_id, deleted: false })
            .first();
        if (!result) {
            return null;
        }
        return result;
    }
    async getConfigIdByProviderConfigKey(providerConfigKey, environment_id) {
        const result = await db.knex
            .select('id')
            .from(`_nango_configs`)
            .where({ unique_key: providerConfigKey, environment_id, deleted: false })
            .first();
        if (!result) {
            return null;
        }
        return result.id;
    }
    async copyProviderConfigCreds(fromEnvironmentId, toEnvironmentId, providerConfigKey) {
        const fromConfig = await this.getProviderConfig(providerConfigKey, fromEnvironmentId);
        if (!fromConfig || !fromConfig.id) {
            return null;
        }
        const { id: foundConfigId, ...configWithoutId } = fromConfig;
        const providerConfigResponse = await this.createProviderConfig({
            ...configWithoutId,
            environment_id: toEnvironmentId,
            unique_key: fromConfig.unique_key
        });
        if (!providerConfigResponse) {
            return null;
        }
        return { copiedToId: providerConfigResponse.id, copiedFromId: foundConfigId };
    }
}
export default new ConfigService();
//# sourceMappingURL=config.service.js.map