import { YagrN8nConfigService } from '../config/n8n-config-service.js';
import { buildManagedN8nWorkflowOpenDataUrl } from '../n8n-local/browser-auth.js';
import { ManagedN8nOwnerCredentialService } from '../n8n-local/owner-credentials.js';
export function resolveWorkflowOpenLink(workflowUrl, options = {}) {
    const targetUrl = normalizeUrl(workflowUrl);
    if (!targetUrl) {
        return {
            openUrl: workflowUrl,
            targetUrl: workflowUrl,
            via: 'direct',
        };
    }
    const n8nConfigService = options.n8nConfigService ?? new YagrN8nConfigService();
    const configuredHost = n8nConfigService.getLocalConfig().host;
    if (configuredHost) {
        const configuredOrigin = normalizeUrl(configuredHost)?.origin;
        if (configuredOrigin && configuredOrigin !== targetUrl.origin) {
            return {
                openUrl: targetUrl.toString(),
                targetUrl: targetUrl.toString(),
                via: 'direct',
            };
        }
    }
    const ownerCredentialService = options.ownerCredentialService ?? new ManagedN8nOwnerCredentialService();
    const ownerCredentials = ownerCredentialService.get(targetUrl.origin);
    if (!ownerCredentials) {
        return {
            openUrl: targetUrl.toString(),
            targetUrl: targetUrl.toString(),
            via: 'direct',
        };
    }
    const loginUrl = new URL('/rest/login', targetUrl.origin).toString();
    return {
        openUrl: buildManagedN8nWorkflowOpenDataUrl({
            targetUrl: targetUrl.toString(),
            loginUrl,
            credentials: ownerCredentials,
        }),
        targetUrl: targetUrl.toString(),
        via: 'self-contained-auth',
    };
}
function normalizeUrl(value) {
    try {
        return new URL(value);
    }
    catch {
        return undefined;
    }
}
//# sourceMappingURL=workflow-links.js.map