import { userNickname } from "../auth0-mgmt"
import { getInstallationOctokitByOwner, isUserCollaborator } from "../github/github-utils"
import { githubApp } from "../github/github-app"

export async function isGitHubAppInstalled(req, res): Promise<void> {
  const { owner, repo } = req.query
  if (!owner || !repo) {
    return res.status(400).send("Missing owner or repo query parameters")
  }
  const ownerStr = String(owner).trim()
  const repoStr = String(repo).trim()
  if (ownerStr === "" || repoStr === "") {
    return res.status(400).send("Invalid owner or repo query parameters")
  }
  const nickname = await userNickname(req.userId)
  if (nickname == null) {
    return res.status(401).send("Unauthorized") // Error getting user nickname
  }
  try {
    const installationOctokit = await getInstallationOctokitByOwner(githubApp, ownerStr, repoStr)
    if (installationOctokit instanceof Error) {
      return res.status(401).send(installationOctokit.message)
    }
    const isCollaborator = await isUserCollaborator(
      installationOctokit,
      ownerStr,
      repoStr,
      nickname,
    )
    if (!isCollaborator) {
      return res
        .status(403)
        .send(
          `The authenticated user is not a collaborator on the repository ${ownerStr}/${repoStr}`,
        )
    }
    res.json(true)
  } catch (error: any) {
    if (error.status === 404) {
      return res
        .status(404)
        .send(`GitHub App is not installed on the repository ${ownerStr}/${repoStr}`)
    }
    console.error("Error checking GitHub App installation or collaborator status:", error)
    res.status(500).send("Error checking GitHub App installation or collaborator status")
  }
}
