"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GovernanceUploadHttpError = void 0;
exports.uploadGovernanceSnapshot = uploadGovernanceSnapshot;
const governanceContracts_1 = require("./governanceContracts");
class GovernanceUploadHttpError extends Error {
    endpoint;
    statusCode;
    response;
    responseMessage;
    constructor(input) {
        const responseMessage = input.responseMessage?.trim() ?? '';
        super(`Governance upload failed with status ${input.statusCode}.${responseMessage ? ` ${responseMessage}` : ''}`);
        this.name = 'GovernanceUploadHttpError';
        this.endpoint = input.endpoint;
        this.statusCode = input.statusCode;
        this.response = input.response;
        this.responseMessage = responseMessage;
    }
}
exports.GovernanceUploadHttpError = GovernanceUploadHttpError;
function resolveUploadEndpoint(serverUrl) {
    const trimmed = serverUrl.trim();
    if (trimmed.length === 0) {
        throw new Error('Governance upload server URL is required.');
    }
    let base;
    try {
        base = new URL(trimmed);
    }
    catch {
        throw new Error('Governance upload server URL is invalid. Use an absolute URL.');
    }
    if (base.protocol !== 'http:' && base.protocol !== 'https:') {
        throw new Error('Governance upload server URL must use http or https.');
    }
    return new URL('/api/v1/governance/uploads', base).toString();
}
function parseResponseBody(raw) {
    if (raw.trim().length === 0) {
        return {};
    }
    try {
        return JSON.parse(raw);
    }
    catch {
        return { message: raw };
    }
}
function extractResponseMessage(parsed) {
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        return '';
    }
    const record = parsed;
    if (typeof record.message === 'string') {
        return record.message.trim();
    }
    if (typeof record.error === 'string') {
        return record.error.trim();
    }
    const nestedError = record.error;
    if (nestedError && typeof nestedError === 'object' && !Array.isArray(nestedError)) {
        const nestedMessage = nestedError.message;
        if (typeof nestedMessage === 'string') {
            return nestedMessage.trim();
        }
    }
    return '';
}
async function uploadGovernanceSnapshot(input) {
    const endpoint = resolveUploadEndpoint(input.serverUrl);
    const timeoutMs = input.timeoutMs ?? 10000;
    const token = input.token.trim();
    if (token.length === 0) {
        throw new Error('Governance upload token is required.');
    }
    const payloadErrors = (0, governanceContracts_1.validateGovernanceUploadPayload)(input.payload);
    if (payloadErrors.length > 0) {
        throw new Error(`Governance upload payload is invalid. ${payloadErrors.join(' ')}`);
    }
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), timeoutMs);
    try {
        const response = await fetch(endpoint, {
            method: 'POST',
            headers: {
                'content-type': 'application/json',
                authorization: `Bearer ${token}`,
            },
            body: JSON.stringify(input.payload),
            signal: controller.signal,
        });
        const raw = await response.text();
        const parsed = parseResponseBody(raw);
        if (!response.ok) {
            throw new GovernanceUploadHttpError({
                endpoint,
                statusCode: response.status,
                response: parsed,
                responseMessage: extractResponseMessage(parsed),
            });
        }
        return {
            endpoint,
            statusCode: response.status,
            response: parsed,
        };
    }
    catch (error) {
        if (error instanceof DOMException && error.name === 'AbortError') {
            throw new Error(`Governance upload timed out after ${timeoutMs}ms.`);
        }
        throw error;
    }
    finally {
        clearTimeout(timeout);
    }
}
//# sourceMappingURL=governanceUploadClient.js.map