"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.gitlabTicketTrackerAuth = exports.gitlabRepositoryHostAuth = void 0;
exports.createGitLabAuthDefinition = createGitLabAuthDefinition;
const branding_1 = require("../../core/branding");
const command_1 = require("../../core/command");
const catalog_1 = require("../../i18n/catalog");
const credential_sources_1 = require("../auth/credential-sources");
const project_ref_1 = require("./project-ref");
const GITLAB_AUTH_TOKEN_ENV_NAMES = [branding_1.ALPACA_GITLAB_TOKEN_ENV_NAME];
function createGitLabAuthDefinition(deps = {}) {
    const commandExistsFn = deps.commandExists ?? command_1.commandExists;
    const runCommandFn = deps.runCommand ?? command_1.runCommand;
    return {
        displayName: "GitLab",
        connectionKey(target) {
            const projectRef = target.projectRef?.trim();
            if (!projectRef) {
                return "gitlab";
            }
            try {
                return `gitlab:${(0, project_ref_1.parseGitLabProjectRef)(projectRef).origin}`;
            }
            catch {
                return "gitlab";
            }
        },
        async resolveCredential(target, env) {
            const envToken = (0, credential_sources_1.resolveTrimmedEnvValue)(env, GITLAB_AUTH_TOKEN_ENV_NAMES);
            if (envToken) {
                return envToken;
            }
            const gitCredential = target.projectRef
                ? buildGitCredentialRequest(target.projectRef)
                : null;
            const credential = gitCredential
                ? await (0, credential_sources_1.resolveUsernamePasswordCredentialFromSources)({
                    env,
                    envPairs: [],
                    gitCredential,
                    commandExists: commandExistsFn,
                    runCommand: runCommandFn,
                })
                : null;
            return credential?.password ?? null;
        },
        async resolveGitCredentials(target, env) {
            const envToken = (0, credential_sources_1.resolveTrimmedEnvValue)(env, GITLAB_AUTH_TOKEN_ENV_NAMES);
            if (envToken) {
                return {
                    username: "oauth2",
                    password: envToken,
                };
            }
            const gitCredential = target.projectRef
                ? buildGitCredentialRequest(target.projectRef)
                : null;
            return gitCredential
                ? (0, credential_sources_1.resolveUsernamePasswordCredentialFromSources)({
                    env,
                    envPairs: [],
                    gitCredential,
                    commandExists: commandExistsFn,
                    runCommand: runCommandFn,
                })
                : null;
        },
        async checkSession(credential, target) {
            const projectRef = target.projectRef?.trim();
            const { origin } = projectRef
                ? (0, project_ref_1.parseGitLabProjectRef)(projectRef)
                : { origin: "https://gitlab.com" };
            const response = await fetch(`${origin}/api/v4/user`, {
                headers: {
                    accept: "application/json",
                    "private-token": credential,
                },
            });
            if (response.ok) {
                return;
            }
            throw new Error(`GitLab authentication failed with status ${response.status}.`);
        },
        getSetupMode() {
            return "external-only";
        },
        async isSetupSupported() {
            return false;
        },
        renderSetupInstructions(_target, locale = catalog_1.DEFAULT_APP_LOCALE) {
            return [
                (0, catalog_1.translate)(locale, "gitlab.auth.setup.exportToken", {
                    envNames: GITLAB_AUTH_TOKEN_ENV_NAMES.join(", "),
                }),
            ];
        },
        getGitCredentials(credential) {
            return {
                username: "oauth2",
                password: credential,
            };
        },
    };
}
const gitlabAuthDefinition = createGitLabAuthDefinition();
exports.gitlabRepositoryHostAuth = gitlabAuthDefinition;
exports.gitlabTicketTrackerAuth = gitlabAuthDefinition;
function buildGitCredentialRequest(projectRef) {
    try {
        const { origin } = (0, project_ref_1.parseGitLabProjectRef)(projectRef);
        const url = new URL(origin);
        return {
            protocol: url.protocol.replace(/:$/, ""),
            host: url.host,
        };
    }
    catch {
        return null;
    }
}
