import fetch from "node-fetch";
import "dotenv/config";

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

export const makePullRequest = async (
  owner: string,
  repoName: string,
  title: string,
  body: string,
  branchName: string,
  reviewers: Array<string>,
  assignee: string = ""
) => {
  const PULL_URL = `${GITEA_API_URL}/${owner}/${repoName}/pulls`;

  const response = await fetch(PULL_URL, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.GITEA_API_KEY}`,
    },
    body: JSON.stringify({
      assignee: assignee,
      base: MAIN_BRANCH,
      title: title,
      body: body,
      head: branchName,
    }),
  });
  const content = await response.json();
  if (response.status != 201) {
    console.log(content);
    throw Error("Error from Gitea when making PR: " + content.errors);
  }

  await addReviewers(reviewers, owner, repoName, content.number);

  return content.url;
};

async function addReviewers(
  reviewers: Array<string>,
  owner: string,
  repoName: string,
  prNumber: number
) {
  const PULL_URL = `${GITEA_API_URL}/${owner}/${repoName}/pulls/${prNumber}/requested_reviewers`;
  const response = await fetch(PULL_URL, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.GITEA_API_KEY}`,
    },
    body: JSON.stringify({
      reviewers: reviewers,
    }),
  });

  const content = await response.json();
  if (response.status != 201) {
    console.log(content);
    throw Error("Error from Gitea when adding reviewers " + content.errors);
  }
  return;
}
