"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GitLabApiError = void 0;
exports.requestGitLab = requestGitLab;
exports.requestGitLabJson = requestGitLabJson;
exports.isGitLabApiError = isGitLabApiError;
exports.isGitLabNotFoundError = isGitLabNotFoundError;
exports.resolveGitLabUserIds = resolveGitLabUserIds;
exports.resolveGitLabUsersByLogin = resolveGitLabUsersByLogin;
const project_ref_1 = require("./project-ref");
class GitLabApiError extends Error {
    status;
    constructor(status, message, name) {
        super(message || `GitLab request failed with status ${status}.`);
        this.status = status;
        this.name = name;
    }
}
exports.GitLabApiError = GitLabApiError;
async function requestGitLab(input) {
    const response = await fetch(input.url, {
        method: input.method,
        headers: {
            accept: "application/json",
            "content-type": "application/json",
            "private-token": input.token,
        },
        ...(input.body === undefined ? {} : { body: JSON.stringify(input.body) }),
    });
    if (!response.ok) {
        throw new GitLabApiError(response.status, await response.text(), input.errorName);
    }
    return response;
}
async function requestGitLabJson(input) {
    const response = await requestGitLab(input);
    if (response.status === 204) {
        return undefined;
    }
    return (await response.json());
}
function isGitLabApiError(error) {
    return error instanceof GitLabApiError;
}
function isGitLabNotFoundError(error) {
    return isGitLabApiError(error) && error.status === 404;
}
async function resolveGitLabUserIds(input) {
    return (await resolveGitLabUsersByLogin(input)).map((user) => user.id);
}
async function resolveGitLabUsersByLogin(input) {
    const normalizedLogins = input.logins
        .map((login) => login.trim())
        .filter((login) => login.length > 0);
    if (normalizedLogins.length === 0) {
        return [];
    }
    const { origin } = (0, project_ref_1.parseGitLabProjectRef)(input.projectRef);
    const usersByLogin = [];
    for (const login of normalizedLogins) {
        const url = new URL(`${origin}/api/v4/users`);
        url.searchParams.set("username", login);
        const users = await requestGitLabJson({
            method: "GET",
            url: url.toString(),
            token: input.token,
            errorName: input.errorName,
        });
        const user = users.find((entry) => entry.username === login);
        if (user) {
            usersByLogin.push({ login, id: user.id });
        }
    }
    return usersByLogin;
}
