import { describe, expect, it } from "vitest";
import { parseGitHubPublicationCredentialConfiguration } from "../../apps/control-plane/src/github-publication.js";

const appEnvironment = {
  AWP_GITHUB_PUBLICATION_APP_ID: "12345",
  AWP_GITHUB_PUBLICATION_INSTALLATION_ID: "67890",
  AWP_GITHUB_PUBLICATION_APP_PRIVATE_KEY_FILE: "/secret/awp-github-app.pem",
  AWP_GITHUB_PUBLICATION_REPOSITORY: "platform-modules/awp",
};

describe("control-plane GitHub publication authority configuration", () => {
  it("keeps publication disabled when neither credential mode is configured", () => {
    expect(parseGitHubPublicationCredentialConfiguration({})).toBeUndefined();
  });

  it("retains the existing static token-file mode", () => {
    expect(
      parseGitHubPublicationCredentialConfiguration({
        AWP_GITHUB_PUBLICATION_TOKEN_FILE: "/secret/publication-token",
      }),
    ).toEqual({ kind: "token-file", tokenFile: "/secret/publication-token" });
  });

  it("accepts one complete GitHub App installation configuration", () => {
    expect(parseGitHubPublicationCredentialConfiguration(appEnvironment)).toEqual({
      kind: "github-app",
      appId: "12345",
      installationId: "67890",
      privateKeyFile: "/secret/awp-github-app.pem",
      repositoryKey: "platform-modules/awp",
    });
  });

  it("fails closed on partial GitHub App configuration", () => {
    expect(() =>
      parseGitHubPublicationCredentialConfiguration({
        AWP_GITHUB_PUBLICATION_APP_ID: "12345",
        AWP_GITHUB_PUBLICATION_INSTALLATION_ID: "67890",
      }),
    ).toThrow("requires app id, installation id, private-key file, and repository");
  });

  it("refuses dual static-token and GitHub App authority", () => {
    expect(() =>
      parseGitHubPublicationCredentialConfiguration({
        ...appEnvironment,
        AWP_GITHUB_PUBLICATION_TOKEN_FILE: "/secret/publication-token",
      }),
    ).toThrow("either token-file or GitHub App configuration, never both");
  });
});
