import { githubApp } from "../github/github-app.js"
import { logger } from "../utils/logger.js"
import { internalServerError } from "../exceptions/index.js"

export async function installedRepositories(req, res, next) {
  try {
    // const installationOctokit = await githubApp.getInstallationOctokit(installationId)
    // const installations = await installationOctokit.rest.apps.listInstallations()

    const installations = await githubApp.octokit.request("GET /app/installations", {
      headers: {
        "X-GitHub-Api-Version": "2022-11-28",
      },
    })

    let allRepos: any[] = []
    for (const installation of installations.data) {
      const installationId = installation.id
      const installationOctokit = await githubApp.getInstallationOctokit(installationId)
      const reposResponse = await installationOctokit.rest.apps.listReposAccessibleToInstallation()
      allRepos = allRepos.concat(reposResponse.data.repositories)
    }

    logger.info("Successfully fetched installed repositories", req, {
      repositoryCount: allRepos.length,
    })

    res.json(allRepos)
  } catch (error) {
    logger.errorWithSentry("Error fetching repositories", req, {}, error as Error)
    next(internalServerError("Error fetching repositories"))
  }
}
