import { githubApp } from "../github/github-app"

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)
    }

    res.json(allRepos)
  } catch (error) {
    console.error("Error fetching repositories:", error)
    res.status(500).send("Error fetching repositories")
    next(error)
  }
}
