"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.githubTicketTrackerAuth = exports.githubRepositoryHostAuth = void 0;
exports.createGitHubAuthDefinition = createGitHubAuthDefinition;
const node_child_process_1 = require("node:child_process");
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 octokit_loader_1 = require("./octokit-loader");
const GITHUB_AUTH_TOKEN_ENV_NAMES = [branding_1.ALPACA_GITHUB_TOKEN_ENV_NAME];
function createGitHubAuthDefinition(deps = {}) {
    const commandExistsFn = deps.commandExists ?? command_1.commandExists;
    const commandExistsSyncFn = deps.commandExistsSync ?? command_1.commandExistsSync;
    const runCommandFn = deps.runCommand ?? command_1.runCommand;
    const runSetup = deps.runSetup ?? defaultRunGitHubSetup;
    return {
        displayName: "GitHub",
        connectionKey() {
            return "github";
        },
        async resolveCredential(_target, env) {
            return (0, credential_sources_1.resolveTokenCredentialFromSources)({
                env,
                envNames: GITHUB_AUTH_TOKEN_ENV_NAMES,
                command: {
                    command: "gh",
                    args: ["auth", "token"],
                    env: buildGitHubCliCredentialEnv(env),
                    timeoutMs: 15_000,
                },
                commandExists: commandExistsFn,
                runCommand: runCommandFn,
            });
        },
        async checkSession(credential) {
            const octokit = await (0, octokit_loader_1.createGitHubOctokit)({ auth: credential });
            await octokit.users.getAuthenticated();
        },
        getSetupMode() {
            return commandExistsSyncFn("gh") ? "inline" : "external-only";
        },
        async isSetupSupported() {
            return commandExistsFn("gh");
        },
        async runSetup(_target, locale) {
            await runSetup(locale);
        },
        renderSetupInstructions(_target, locale = catalog_1.DEFAULT_APP_LOCALE) {
            return [
                (0, catalog_1.translate)(locale, "github.auth.setup.runGhAuthLogin"),
                (0, catalog_1.translate)(locale, "github.auth.setup.exportToken", {
                    envNames: GITHUB_AUTH_TOKEN_ENV_NAMES.join(", "),
                }),
            ];
        },
        getGitCredentials(credential) {
            return {
                username: "x-access-token",
                password: credential,
            };
        },
    };
}
function buildGitHubCliCredentialEnv(env) {
    const commandEnv = { ...process.env, ...env };
    for (const legacyEnvName of ["GITHUB_TOKEN", "GH_TOKEN"]) {
        delete commandEnv[legacyEnvName];
    }
    return commandEnv;
}
const githubAuthDefinition = createGitHubAuthDefinition();
exports.githubRepositoryHostAuth = githubAuthDefinition;
exports.githubTicketTrackerAuth = githubAuthDefinition;
async function defaultRunGitHubSetup(locale = catalog_1.DEFAULT_APP_LOCALE) {
    await new Promise((resolve, reject) => {
        const child = (0, node_child_process_1.spawn)("gh", ["auth", "login"], {
            stdio: "inherit",
            env: process.env,
        });
        child.on("error", reject);
        child.on("exit", (code) => {
            if (code === 0) {
                resolve();
                return;
            }
            reject(new Error((0, catalog_1.translate)(locale, "github.auth.setup.failed", {
                code: code ?? 1,
            })));
        });
    });
}
