"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntegrationsClient = void 0;
const logger_1 = require("../utils/logger");
const ConfigManager_1 = require("./ConfigManager");
const AuthService_1 = require("./AuthService");
const accessTokenRefresh_1 = require("./accessTokenRefresh");
const log = (0, logger_1.createLogger)('IntegrationsClient');
/**
 * Calls the Rivet proxy's authenticated integration endpoints using the
 * machine's validated bearer token (refreshing once on a 401, mirroring
 * AuthService.getValidatedProfile).
 */
class IntegrationsClient {
    proxyUrl;
    configManager = (0, ConfigManager_1.getConfigManager)();
    authService;
    constructor(options) {
        this.proxyUrl = options?.proxyUrl || this.configManager.getProxyUrl();
        this.authService = options?.authService ?? new AuthService_1.AuthService(this.proxyUrl);
    }
    /**
     * Fetch normalized Pinterest data for a pin/board URL. Returns the proxy's
     * structured result, including the soft `not_connected` payload when the
     * user has not connected Pinterest.
     */
    async fetchPinterest(url) {
        let token = this.configManager.getAuthToken();
        if (!token) {
            // The MCP tool guard validates auth before this runs, but fall back to a
            // full validation (which can refresh) to surface a live token.
            const profile = await this.authService.getValidatedProfile();
            token = this.configManager.getAuthToken();
            if (!profile || !token) {
                return { status: 'error', message: 'Not authenticated' };
            }
        }
        const post = async (bearer) => fetch(`${this.proxyUrl}/api/integrations/pinterest/fetch`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${bearer}`,
            },
            body: JSON.stringify({ url }),
        });
        try {
            let response = await post(token);
            // Token rejected — refresh once and retry, matching AuthService.
            if (response.status === 401) {
                const refreshToken = this.configManager.getRefreshToken();
                if (refreshToken) {
                    const refreshed = await (0, accessTokenRefresh_1.refreshAccessTokenViaProxy)({
                        refreshToken,
                        proxyUrl: this.proxyUrl,
                    });
                    if (refreshed) {
                        this.configManager.setAuth(refreshed.token, this.configManager.getEmail() || '', refreshed.refreshToken);
                        response = await post(refreshed.token);
                    }
                }
            }
            if (!response.ok) {
                const text = await response.text().catch(() => '');
                return {
                    status: 'error',
                    message: `Pinterest fetch failed (${response.status}): ${text.slice(0, 200)}`,
                };
            }
            return (await response.json());
        }
        catch (error) {
            log.warn('Pinterest fetch error:', error);
            return {
                status: 'error',
                message: error instanceof Error ? error.message : 'Unknown error',
            };
        }
    }
}
exports.IntegrationsClient = IntegrationsClient;
//# sourceMappingURL=IntegrationsClient.js.map