const SENTRY_BASE = 'https://sentry.io/api/0';
function isValidLevel(level) {
    return ['fatal', 'error', 'warning', 'info', 'debug'].includes(level);
}
function mapIssue(raw) {
    const level = isValidLevel(raw.level) ? raw.level : 'error';
    return {
        id: raw.id,
        title: raw.title,
        culprit: raw.culprit,
        level,
        count: parseInt(raw.count, 10) || 0,
        userCount: raw.userCount,
        firstSeen: raw.firstSeen,
        lastSeen: raw.lastSeen,
        isResolved: raw.isResolved,
        permalink: raw.permalink,
        tags: raw.tags ?? [],
    };
}
function buildHeaders(authToken) {
    return {
        Authorization: `Bearer ${authToken}`,
        'Content-Type': 'application/json',
    };
}
export async function fetchSentryIssues(config, limit, level, unresolved) {
    const params = new URLSearchParams();
    params.set('limit', String(limit));
    if (unresolved !== false) {
        params.set('query', 'is:unresolved');
    }
    if (level !== undefined && level !== '') {
        params.set('query', `${params.get('query') ?? ''} level:${level}`.trim());
    }
    const url = `${SENTRY_BASE}/projects/${config.organizationSlug}/${config.projectSlug}/issues/?${params.toString()}`;
    const response = await fetch(url, { headers: buildHeaders(config.authToken) });
    if (!response.ok) {
        throw new Error(`Sentry API error ${response.status}: ${response.statusText}`);
    }
    const data = (await response.json());
    return data.map(mapIssue);
}
export async function fetchSentryIssue(config, issueId) {
    const url = `${SENTRY_BASE}/issues/${issueId}/`;
    const response = await fetch(url, { headers: buildHeaders(config.authToken) });
    if (!response.ok) {
        throw new Error(`Sentry API error ${response.status}: ${response.statusText}`);
    }
    const data = (await response.json());
    return mapIssue(data);
}
export async function fetchIssueStacktrace(config, issueId) {
    const url = `${SENTRY_BASE}/issues/${issueId}/events/latest/`;
    const response = await fetch(url, { headers: buildHeaders(config.authToken) });
    if (!response.ok) {
        return '(stacktrace not available)';
    }
    const event = (await response.json());
    const exceptionEntry = event.entries?.find((e) => e.type === 'exception');
    const values = exceptionEntry?.data?.values ?? [];
    const firstValue = values[0];
    const frames = firstValue?.stacktrace?.frames ?? [];
    if (frames.length === 0) {
        return '(no frames available)';
    }
    const topFrames = frames.slice(-3).reverse();
    return topFrames
        .map((f) => `  at ${f.function ?? '(unknown)'} (${f.filename ?? '(unknown)'}:${f.lineno ?? '?'})`)
        .join('\n');
}
//# sourceMappingURL=sentry-client.js.map