import { type Repository } from "./dataTypes.ts"

type FlatPatchRecord = {
  commit: ReturnType<Repository['commits']['get']>,
  repoName: string,
  branchName: string,
}

let cachedFlatPatches: Array<FlatPatchRecord> | null = null

export default async (repos: Array<Repository>)
  : Promise<Array<FlatPatchRecord>> => {
  if (cachedFlatPatches !== null) { return cachedFlatPatches }

  cachedFlatPatches = repos.flatMap((repo) => {
    return repo.branches.flatMap((branch) => {
      const flatPatches: Array<FlatPatchRecord> = []
      let currentCommit: ReturnType<Repository['commits']['get']> | undefined = repo.commits.get(branch.head)

      while (currentCommit !== undefined) {
        flatPatches.push({
          commit: currentCommit,
          repoName: repo.name,
          branchName: branch.name
        })

        currentCommit = repo.commits.get(currentCommit.parent)
      }

      return flatPatches
    })
  })

  return cachedFlatPatches
}
