import { describe, expect, test } from "vitest";

import { inspectPublicGit } from "./publicGit";

const source = {
  host: "git.openputer.com",
  normalizedUrl: "https://git.openputer.com/sai-karthik/hello-world",
  projectName: "hello-world",
  repositoryPath: "Sai-karthik/hello-world",
  url: "https://git.openputer.com/Sai-karthik/hello-world.git",
};

describe("public Git repository inspection", () => {
  test("imports metadata for an empty public Gitea repository", async () => {
    const requests: string[] = [];
    const result = await inspectPublicGit(source, {
      fetch(input) {
        const url = String(input);
        requests.push(url);
        if (url.endsWith("/api/v1/repos/Sai-karthik/hello-world")) {
          return Promise.resolve(
            Response.json({
              default_branch: "main",
              empty: true,
            })
          );
        }
        return Promise.resolve(new Response("not found", { status: 404 }));
      },
    });

    expect(result).toMatchObject({
      defaultBranch: "main",
      documents: [],
    });
    expect(result.warnings).toHaveLength(6);
    expect(requests).toContain(
      "https://git.openputer.com/api/v1/repos/Sai-karthik/hello-world"
    );
    expect(requests).toContain(
      "https://git.openputer.com/api/v1/repos/Sai-karthik/hello-world/raw/README.md?ref=main"
    );
  });

  test("rejects hosts outside the supported provider allowlist", async () => {
    await expect(
      inspectPublicGit({
        ...source,
        host: "example.com",
        normalizedUrl: "https://example.com/example/repository",
        repositoryPath: "example/repository",
        url: "https://example.com/example/repository.git",
      })
    ).rejects.toThrow(
      "Repository import supports public GitHub and git.openputer.com URLs"
    );
  });
});
