"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = run;
const core = __importStar(require("@actions/core"));
const sdk_napi_1 = require("@bitwarden/sdk-napi");
const parser_1 = require("./parser");
async function run() {
    try {
        const inputs = readInputs();
        core.info("🔑 Logging into Bitwarden...");
        const client = await getBitwardenClient(inputs);
        const secretInputs = (0, parser_1.parseSecretInput)(inputs.secrets);
        core.info("🔍 Retrieving secrets...");
        await retrieveAndSetSecrets(client, secretInputs);
        core.info("✅ Successfully retrieved and set secrets!");
    }
    catch (error) {
        core.setFailed(`❌ Error: ${error instanceof Error ? error.message : error}`);
    }
}
function readInputs() {
    const clientId = core.getInput("client-id", { required: true });
    const clientSecret = core.getInput("client-secret", { required: true });
    const password = core.getInput("password", { required: true });
    const server = core.getInput("server", { required: true }); // Je eigen Bitwarden server
    const secretsRaw = core.getInput("secrets", { required: true });
    const secrets = secretsRaw
        .split("\n")
        .map((s) => s.trim())
        .filter((s) => s.includes(">"));
    if (secrets.length === 0) {
        throw new Error("No valid secrets provided.");
    }
    return { clientId, clientSecret, password, server, secrets };
}
async function retrieveAndSetSecrets(client, secretsInput) {
    const secretIds = secretsInput.map((secret) => secret.id);
    const secretResponse = await client.secrets().getByIds(secretIds);
    if (secretResponse.success && secretResponse.data) {
        const fetchedSecrets = secretResponse.data.data;
        fetchedSecrets.forEach((secret) => {
            const secretInput = secretsInput.find((input) => input.id === secret.id);
            if (secretInput) {
                core.setSecret(secret.value);
                core.exportVariable(secretInput.outputEnvName, secret.value);
                core.setOutput(secretInput.outputEnvName, secret.value);
            }
        });
    }
    else {
        throw new Error(`The secrets provided could not be found. Please check the machine account has access to the secret UUIDs provided.\nError: ${secretResponse.errorMessage}`);
    }
    core.info("✅ Completed setting secrets as environment variables.");
}
async function getBitwardenClient(inputs) {
    const settings = {
        identityUrl: `${inputs.server}/identity`,
        apiUrl: `${inputs.server}/api`,
        userAgent: "actions/warden",
        deviceType: sdk_napi_1.DeviceType.SDK,
    };
    const client = new sdk_napi_1.BitwardenClient(settings, 2 /* LogLevel.Info */);
    const result = await client.loginWithAccessToken(inputs.clientSecret);
    if (!result.success) {
        throw Error(`Authentication with Bitwarden failed.\nError: ${result.errorMessage}`);
    }
    return client;
}
