"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureGiteaRepositoryExists = ensureGiteaRepositoryExists;
const auth_1 = require("./auth");
const project_ref_1 = require("./project-ref");
async function ensureGiteaRepositoryExists(input) {
    const project = (0, project_ref_1.parseGiteaProjectRef)(input.projectRef);
    const authorization = (0, auth_1.toGiteaAuthorizationHeader)(input.credential);
    const repositoryPath = `/repos/${encodeURIComponent(project.owner)}/${encodeURIComponent(project.repo)}`;
    const existing = await fetch((0, project_ref_1.buildGiteaApiUrl)(input.projectRef, repositoryPath), {
        headers: buildGiteaHeaders(authorization),
    });
    if (existing.ok) {
        return {
            created: false,
            remoteUrl: (0, project_ref_1.buildGiteaRemoteUrl)(input.projectRef),
        };
    }
    if (existing.status !== 404) {
        throw new Error(await formatGiteaError(existing, "checking repository"));
    }
    await input.beforeCreate?.();
    const createPath = await resolveRepositoryCreatePath({
        projectRef: input.projectRef,
        owner: project.owner,
        authorization,
    });
    const created = await fetch((0, project_ref_1.buildGiteaApiUrl)(input.projectRef, createPath), {
        method: "POST",
        headers: {
            ...buildGiteaHeaders(authorization),
            "content-type": "application/json",
        },
        body: JSON.stringify(Object.fromEntries([
            ["name", project.repo],
            ["default_branch", input.defaultBranch],
        ])),
    });
    if (!created.ok) {
        throw new Error(await formatGiteaError(created, "creating repository"));
    }
    return {
        created: true,
        remoteUrl: (0, project_ref_1.buildGiteaRemoteUrl)(input.projectRef),
    };
}
async function resolveRepositoryCreatePath(input) {
    const response = await fetch((0, project_ref_1.buildGiteaApiUrl)(input.projectRef, "/user"), {
        headers: buildGiteaHeaders(input.authorization),
    });
    if (!response.ok) {
        throw new Error(await formatGiteaError(response, "checking authenticated user"));
    }
    const user = (await response.json());
    const login = typeof user.login === "string" ? user.login : user.username;
    if (login === input.owner) {
        return "/user/repos";
    }
    return `/orgs/${encodeURIComponent(input.owner)}/repos`;
}
function buildGiteaHeaders(authorization) {
    return {
        accept: "application/json",
        authorization,
    };
}
async function formatGiteaError(response, action) {
    let message = "";
    try {
        const body = (await response.json());
        message = typeof body.message === "string" ? body.message : "";
    }
    catch {
        // keep the status-only message
    }
    const suffix = message.trim() ? `: ${message.trim()}` : "";
    return `Gitea ${action} failed with status ${response.status}${suffix}`;
}
