/**
 * User context service: resolves the authenticated user's identity and billing context.
 *
 * Fetches user/team/subscription metadata from the Shortcut API using the
 * OAuth access token.
 */
import { SHORTCUT_API_URL } from '../../constants.js';
import { SHORTCUT_API_ENDPOINTS } from '../../endpoints.js';
const TEAM_RESOURCE_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function isRecord(value) {
    return typeof value === 'object' && value !== null;
}
function parseTeamId(value) {
    if (!isRecord(value))
        return null;
    const teamId = value.teamId;
    return typeof teamId === 'string' && TEAM_RESOURCE_ID_PATTERN.test(teamId) ? teamId : null;
}
function stableUniqueTeamIds(values) {
    return Array.from(new Set(values.map((value) => parseTeamId(value)).filter((teamId) => !!teamId))).sort();
}
export function parseAuthorizedSkillTeamIds(data) {
    if (Array.isArray(data.authorizedSkillTeams)) {
        return stableUniqueTeamIds(data.authorizedSkillTeams);
    }
    const byType = isRecord(data.authorizedResourceTeamsByType)
        ? data.authorizedResourceTeamsByType
        : {};
    return Array.isArray(byType.skills) ? stableUniqueTeamIds(byType.skills) : [];
}
/**
 * Fetch user identity from the Shortcut API.
 * Returns null on any failure; never throws.
 */
export async function fetchUserInfo(accessToken, options) {
    const apiUrl = options?.apiUrl ?? SHORTCUT_API_URL;
    const fetchFn = options?.fetch ?? globalThis.fetch;
    try {
        const response = await fetchFn(`${apiUrl}${SHORTCUT_API_ENDPOINTS.userMeWithSubscription}`, {
            headers: { Authorization: `Bearer ${accessToken}` },
            signal: AbortSignal.timeout(10_000)
        });
        if (!response.ok)
            return null;
        const data = (await response.json());
        if (!data.id)
            return null;
        const hasPlan = Object.prototype.hasOwnProperty.call(data, 'plan');
        return {
            userId: data.id,
            email: data.email ?? undefined,
            teamId: data.teamId ?? undefined,
            enterpriseRole: data.enterpriseRole ?? undefined,
            plan: hasPlan ? (data.plan ?? null) : undefined,
            proCreditsTier: data.proCreditsTier ?? null,
            authorizedSkillTeamIds: parseAuthorizedSkillTeamIds(data)
        };
    }
    catch {
        return null;
    }
}
//# sourceMappingURL=user-context.js.map