const core = require("@actions/core");
const _ = require("underscore");

async function getAndPostPullRequests() {
  try {
    core.info("Starting the action...");

    // Retrieve inputs and token
    const baseUrl = core.getInput("base_url") || "https://git.horstenkamp.eu";
    core.info(`Base URL: ${baseUrl}`);

    const owner = core.getInput("owner") || process.env.GITHUB_REPOSITORY_OWNER;
    core.info(`Repository Owner: ${owner}`);

    const repo =
      core.getInput("repo") || process.env.GITHUB_REPOSITORY.split("/")[1];
    core.info(`Repository Name: ${repo}`);

    const branch = core.getInput("branch");
    core.info(`The branch ${branch} should be merged.`);

    const base_branch = core.getInput("base_branch");
    core.info(`The branch ${base_branch} should be merged into.`);

    // core.info(`Post Data: ${JSON.stringify(postData)}`);

    const githubToken = core.getInput("github_token");
    core.info("GitHub token retrieved.");

    // Headers with Authorization
    const headers = {
      Authorization: `token ${githubToken}`,
      "Content-Type": "application/json",
    };

    // Construct the URL for the requests
    const url = `${baseUrl}/api/v1/repos/${owner}/${repo}/pulls`;
    core.info(`Constructed URL: ${url}`);

    // Perform the GET request
    core.info("Performing GET request...");
    const get_url = `${url}?state=open`;
    const getResponse = await fetch(get_url, { headers });

    if (!getResponse.ok) {
      throw new Error(`HTTP error! status: ${getResponse.status}`);
    }

    const pulls = await getResponse.json();
    core.info(`GET request completed. Number of pulls: ${pulls.length}`);
    core.info(`GET repsonse ${JSON.stringify(pulls, 2)}`);

    // Logic to decide if a POST request is needed
    const targetPRFound = _.any(
      pulls,
      (pr) => pr.head.ref === branch && pr.base.ref === base_branch,
    );
    if (targetPRFound) {
      core.info(
        `No open pulls found, to merge ${branch} into ${base_branch}. Trying to create a new PR.`,
      );
      return { message: "Abort for thesting" };
      // Perform the POST request
      const postResponse = await fetch(url, {
        method: "POST",
        headers,
        body: JSON.stringify(postData),
      });

      if (!postResponse.ok) {
        throw new Error(`HTTP error! status: ${postResponse.status}`);
      }

      const postResult = await postResponse.json();
      core.info("POST request completed successfully.");
      return postResult;
    } else {
      core.info(
        `There is already an PR for open that merges ${branch} into ${base_branch}.`,
      );
      return {
        message: `There is already an PR for open that merges ${branch} into ${base_branch}.`,
      };
    }
  } catch (error) {
    core.setFailed(`Action failed with error: ${error}`);
  }
}

// Call the function
getAndPostPullRequests();
