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

type BranchEntry = {
  relName: string,
  type: "branch",
  repoName: string,
  compareTo: string,
  ahead: number,
  behind: number,
}

type TagEntry = {
  relName: string,
  type: "tag",
  repoName: string,
}

let cachedRels: Array<BranchEntry | TagEntry> | null = null

export default (repos: Array<Repository>) => {
  if (cachedRels !== null) { return cachedRels }

  cachedRels = repos.flatMap((repo) => {
    const branches: Array<BranchEntry> = repo.branches.map((branch) => {
      const result: BranchEntry = {
        relName: branch.name,
        type: "branch",
        repoName: repo.name,
        compareTo: branch.compareTo,
        ahead: branch.ahead,
        behind: branch.behind,
      }
      if (branch.description) { result['description'] = branch.description }
      return result
    })
    const tags: Array<TagEntry> = repo.tags.map((tag) => {
      return {
        relName: tag.name,
        type: "tag",
        repoName: repo.name,
      }
    })

    return [...branches, ...tags]
  })

  return cachedRels
}
