import fetch from "node-fetch";

export const MAIN_BRANCH = "main";
export const GITEA_API_URL = "https://git.csclub.uwaterloo.ca/api/v1/repos";

export interface PullRequestResult {
  created: boolean;
  url: string | null;
  reason: string;
}

// Opens a PR against {baseOwner}/{repoName}:main from {headOwner}/{branchName}
// (headOwner may equal baseOwner if pushing directly rather than to a fork).
// If no GITEA_API_KEY is configured, this logs what it would have done and
// returns created: false instead of throwing -- see .env.example.
export async function makePullRequest(
  baseOwner: string,
  repoName: string,
  headOwner: string,
  branchName: string,
  title: string,
  body: string
): Promise<PullRequestResult> {
  const apiKey = process.env.GITEA_API_KEY;
  const head = headOwner === baseOwner ? branchName : `${headOwner}:${branchName}`;

  if (!apiKey) {
    const reason = `GITEA_API_KEY not configured; would have opened PR ${baseOwner}/${repoName} base=${MAIN_BRANCH} head=${head} title="${title}"`;
    console.warn(reason);
    return { created: false, url: null, reason };
  }

  const pullUrl = `${GITEA_API_URL}/${baseOwner}/${repoName}/pulls`;
  const response = await fetch(pullUrl, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      base: MAIN_BRANCH,
      head,
      title,
      body,
    }),
  });

  const content = await response.json();
  if (response.status !== 201) {
    throw new Error(`Gitea PR creation failed (${response.status}): ${JSON.stringify(content)}`);
  }

  return { created: true, url: content.html_url ?? content.url, reason: "created" };
}
