import { LogActionEnum } from '../../../models/Activity.js';
import { createActivityLogAndLogMessage } from '../../../services/activity/activity.service.js';
import proxyService from '../../../services/proxy.service.js';
import connectionService from '../../../services/connection.service.js';
import environmentService from '../../../services/environment.service.js';
import telemetry, { LogTypes } from '../../../utils/telemetry.js';
import * as postConnectionHandlers from './index.js';
import { stringifyError } from '@nangohq/utils';
const handlers = postConnectionHandlers;
async function execute(createdConnection, provider, logContextGetter) {
    const { connection_id, environment_id, provider_config_key } = createdConnection;
    try {
        const accountId = await environmentService.getAccountIdFromEnvironment(environment_id);
        const { success, response: connection } = await connectionService.getConnectionCredentials(accountId, environment_id, connection_id, provider_config_key, logContextGetter);
        if (!success || !connection) {
            return;
        }
        const internalConfig = {
            connection,
            provider
        };
        const externalConfig = {
            endpoint: '',
            connectionId: connection.connection_id,
            providerConfigKey: connection.provider_config_key,
            method: 'GET',
            data: {}
        };
        const internalNango = {
            getConnection: async () => {
                const { response: connection } = await connectionService.getConnection(connection_id, provider_config_key, environment_id);
                return connection;
            },
            proxy: async ({ method, endpoint, data }) => {
                const finalExternalConfig = { ...externalConfig, method: method || externalConfig.method, endpoint };
                if (data) {
                    finalExternalConfig.data = data;
                }
                const { response } = await proxyService.route(finalExternalConfig, internalConfig);
                return response;
            },
            updateConnectionConfig: (connectionConfig) => {
                return connectionService.updateConnectionConfig(connection, connectionConfig);
            }
        };
        const handler = handlers[`${provider.replace(/-/g, '')}PostConnection`];
        if (handler) {
            try {
                await handler(internalNango);
            }
            catch (e) {
                const errorDetails = e instanceof Error
                    ? {
                        message: e.message || 'Unknown error',
                        name: e.name || 'Error',
                        stack: e.stack || 'No stack trace'
                    }
                    : 'Unknown error';
                const errorString = JSON.stringify(errorDetails);
                const log = {
                    level: 'error',
                    success: false,
                    action: LogActionEnum.AUTH,
                    start: Date.now(),
                    end: Date.now(),
                    timestamp: Date.now(),
                    connection_id: connection_id,
                    provider,
                    provider_config_key: provider_config_key,
                    environment_id
                };
                const activityLogId = await createActivityLogAndLogMessage(log, {
                    level: 'error',
                    environment_id: environment_id,
                    timestamp: Date.now(),
                    content: `Post connection script failed with the error: ${errorString}`
                });
                const logCtx = await logContextGetter.create({ id: String(activityLogId), operation: { type: 'token' }, message: 'Authentication' }, {
                    account: { id: accountId },
                    environment: { id: connection.environment_id },
                    config: { id: connection.config_id, name: connection.provider_config_key },
                    connection: { id: connection.id, name: connection.connection_id }
                });
                await logCtx.error('Post connection script failed', { error: e });
                await logCtx.failed();
                await telemetry.log(LogTypes.POST_CONNECTION_SCRIPT_FAILURE, `Post connection script failed, ${errorString}`, LogActionEnum.AUTH, {
                    environmentId: String(environment_id),
                    connectionId: connection_id,
                    providerConfigKey: provider_config_key,
                    provider: provider,
                    level: 'error'
                });
            }
        }
    }
    catch (err) {
        await telemetry.log(LogTypes.POST_CONNECTION_SCRIPT_FAILURE, `Post connection manager failed, ${stringifyError(err)}`, LogActionEnum.AUTH, {
            environmentId: String(environment_id),
            connectionId: connection_id,
            providerConfigKey: provider_config_key,
            provider: provider,
            level: 'error'
        });
    }
}
export default execute;
//# sourceMappingURL=connection.manager.js.map