import { logger } from "../../common/logger.js";
import { printSpinnerToConsole } from "../../common/output.js";
import settings from "../../common/settings.js";
export class ProjectCreationError extends Error {
    retryable;
    constructor(message, retryable, options) {
        super(message, options);
        this.retryable = retryable;
        this.name = "ProjectCreationError";
    }
}
export async function create(argv) {
    const account = argv.account;
    if (!account) {
        throw new Error("Invalid state: account is not set.");
    }
    if (!argv.name || typeof argv.name !== "string") {
        throw new Error("Invalid state: name is not set.");
    }
    try {
        await createProject({
            name: argv.name,
            account,
            authToken: argv.authToken,
        });
    }
    catch {
        process.exit(1);
    }
    process.exit(0);
}
export async function createProject({ name, account, authToken, }) {
    const spinner = printSpinnerToConsole(`Creating project ${name} for account ${account}...`);
    let response;
    try {
        response = await fetch(`${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/projects?accountName=${encodeURIComponent(account)}`, {
            method: "POST",
            headers: {
                Authorization: `Bearer ${authToken}`,
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                name,
            }),
        });
    }
    catch (cause) {
        logger.error(cause, "Network error creating project");
        spinner.fail("Network error: could not reach the server.");
        throw new ProjectCreationError("Network error: could not reach the server.", false, { cause });
    }
    if (!response.ok) {
        let errorJson;
        try {
            errorJson = await response.json();
        }
        catch {
        }
        const detail = typeof errorJson?.detail === "string" ? errorJson.detail : undefined;
        const title = typeof errorJson?.title === "string" ? errorJson.title : undefined;
        const message = detail ?? title ?? "Failed to create project.";
        logger.error(errorJson, "Failed to create project.");
        spinner.fail(message);
        throw new ProjectCreationError(message, response.status === 422);
    }
    spinner.succeed(`Project ${name} created successfully.`);
}
//# sourceMappingURL=handler.js.map