import { readFileSync } from "node:fs";
import { createApiClient } from "../../common/api/client.js";
import { logger } from "../../common/logger.js";
import { printDiagnosticsToConsole, printJsonToConsoleAndExitGracefully, printResultToConsole, } from "../../common/output.js";
import { isValidationError, parseAndValidateCaCertificate, validateName, } from "../validation.js";
export async function create(argv) {
    const { account } = argv;
    const nameError = validateName(argv.name);
    if (nameError) {
        printDiagnosticsToConsole(`Error: --name is invalid. ${nameError.message}`);
        return;
    }
    let certificate;
    try {
        certificate = readFileSync(argv.cert, "utf-8");
    }
    catch (error) {
        logger.error(error, "Failed to read CA certificate file");
        printDiagnosticsToConsole(`Error: Failed to read CA certificate file at ${argv.cert}`, error instanceof Error ? error.message : String(error));
        return;
    }
    const parsed = parseAndValidateCaCertificate(certificate);
    if (isValidationError(parsed)) {
        printDiagnosticsToConsole(`Error: ${argv.cert} is not a valid CA certificate. ${parsed.message}`, parsed.hint);
        return;
    }
    const client = createApiClient({ authToken: argv.authToken });
    const cert = await client.post(`/v1/accounts/${account}/client-mtls-ca-certificates`, {
        operation: "Failed to create CA certificate",
        errorMessage: "Error: Failed to create CA certificate. Check the arguments.",
        body: {
            name: argv.name,
            certificate,
        },
    });
    if (argv.output === "json") {
        await printJsonToConsoleAndExitGracefully(cert);
        return;
    }
    const subject = cert.certificateInfo.subject.replace(/\n/g, ", ");
    printResultToConsole(`CA certificate '${cert.name}' (${cert.id}) created successfully\n` +
        `  Subject: ${subject}\n` +
        `  Valid from: ${cert.certificateInfo.validFrom}\n` +
        `  Valid to: ${cert.certificateInfo.validTo}`);
}
//# sourceMappingURL=handler.js.map