"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.giteaTicketTrackerAuth = exports.giteaRepositoryHostAuth = void 0;
exports.buildGiteaBasicCredential = buildGiteaBasicCredential;
exports.toGiteaAuthorizationHeader = toGiteaAuthorizationHeader;
exports.decodeGiteaBasicCredential = decodeGiteaBasicCredential;
exports.createGiteaAuthDefinition = createGiteaAuthDefinition;
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 GITEA_AUTH_CREDENTIAL_ENV = {
    username: branding_1.ALPACA_GITEA_USERNAME_ENV_NAME,
    password: branding_1.ALPACA_GITEA_PASSWORD_ENV_NAME,
};
function buildGiteaBasicCredential(username, password) {
    return `basic:${Buffer.from(`${username}:${password}`, "utf8").toString("base64")}`;
}
function toGiteaAuthorizationHeader(credential) {
    if (!credential.startsWith("basic:")) {
        throw new Error("Unsupported Gitea credential format.");
    }
    return `Basic ${credential.slice("basic:".length)}`;
}
function decodeGiteaBasicCredential(credential) {
    if (!credential.startsWith("basic:")) {
        throw new Error("Unsupported Gitea credential format.");
    }
    const decoded = Buffer.from(credential.slice("basic:".length), "base64").toString("utf8");
    const separatorIndex = decoded.indexOf(":");
    if (separatorIndex < 0) {
        throw new Error("Malformed Gitea credential.");
    }
    return {
        username: decoded.slice(0, separatorIndex),
        password: decoded.slice(separatorIndex + 1),
    };
}
function createGiteaAuthDefinition(deps = {}) {
    const commandExistsFn = deps.commandExists ?? command_1.commandExists;
    const runCommandFn = deps.runCommand ?? command_1.runCommand;
    return {
        displayName: "Gitea",
        connectionKey(target) {
            const projectRef = target.projectRef?.trim();
            if (!projectRef) {
                return "gitea";
            }
            try {
                return `gitea:${(0, project_ref_1.parseGiteaProjectRef)(projectRef).origin}`;
            }
            catch {
                return "gitea";
            }
        },
        async resolveCredential(target, env) {
            const projectRef = target.projectRef?.trim();
            const gitCredential = projectRef
                ? buildGitCredentialRequest(projectRef)
                : null;
            const credential = await (0, credential_sources_1.resolveUsernamePasswordCredentialFromSources)({
                env,
                envPairs: [GITEA_AUTH_CREDENTIAL_ENV],
                ...(gitCredential ? { gitCredential } : {}),
                commandExists: commandExistsFn,
                runCommand: runCommandFn,
            });
            return credential
                ? buildGiteaBasicCredential(credential.username, credential.password)
                : null;
        },
        async checkSession(credential, target) {
            const projectRef = target.projectRef?.trim();
            if (!projectRef) {
                throw new Error("Gitea projectRef is required to validate credentials.");
            }
            const response = await fetch(`${(0, project_ref_1.parseGiteaProjectRef)(projectRef).origin}/api/v1/user`, {
                headers: {
                    accept: "application/json",
                    authorization: toGiteaAuthorizationHeader(credential),
                },
            });
            if (response.ok) {
                return;
            }
            let reason = `Gitea authentication failed with status ${response.status}.`;
            try {
                const body = (await response.json());
                if (typeof body.message === "string" &&
                    body.message.trim().length > 0) {
                    reason = body.message;
                }
            }
            catch {
                // ignore parse failures and keep the status message
            }
            throw new Error(reason);
        },
        getSetupMode() {
            return "external-only";
        },
        async isSetupSupported() {
            return false;
        },
        renderSetupInstructions(_target, locale = catalog_1.DEFAULT_APP_LOCALE) {
            return [
                (0, catalog_1.translate)(locale, "gitea.auth.setup.exportCredentials", {
                    usernameEnvName: GITEA_AUTH_CREDENTIAL_ENV.username,
                    passwordEnvName: GITEA_AUTH_CREDENTIAL_ENV.password,
                }),
            ];
        },
        getGitCredentials(credential) {
            return decodeGiteaBasicCredential(credential);
        },
    };
}
const giteaAuthDefinition = createGiteaAuthDefinition();
exports.giteaRepositoryHostAuth = giteaAuthDefinition;
exports.giteaTicketTrackerAuth = giteaAuthDefinition;
function buildGitCredentialRequest(projectRef) {
    try {
        const { origin } = (0, project_ref_1.parseGiteaProjectRef)(projectRef);
        const url = new URL(origin);
        return {
            protocol: url.protocol.replace(/:$/, ""),
            host: url.host,
        };
    }
    catch {
        return null;
    }
}
