const { getUpdateStatus } = require("./update-index");
const { applyCoreUpdate } = require("./repo-update");
const {
  normalizeRepositoryTarget,
  resolveSourceBranch
} = require("./update-repository");

function normalizeUpdateSource(branch) {
  const requested = String(branch || "main").trim();
  if (requested === "main" || requested === "stable") return "stable";
  if (requested === "experimental") return "experimental";
  return requested || "stable";
}

function checkForUpdates(remote, branch) {
  const target = normalizeRepositoryTarget(remote);
  const source = normalizeUpdateSource(branch);
  const status = getUpdateStatus({ remote: target, source });
  return Boolean(status.core?.update_available);
}

async function pullUpdates(remote, branch) {
  const target = normalizeRepositoryTarget(remote);
  const source = normalizeUpdateSource(branch);
  const result = await applyCoreUpdate({ remote: target, source });
  return `Applied core update from ${result.target.source_branch}.`;
}

function resolveUpdateBranch(remote, branch) {
  return resolveSourceBranch(normalizeRepositoryTarget(remote), normalizeUpdateSource(branch));
}

function requestRestart() {
  setTimeout(() => process.exit(10), 500);
}

module.exports = {
  checkForUpdates,
  pullUpdates,
  normalizeRepositoryTarget,
  resolveUpdateBranch,
  requestRestart
};
