import { getRepositoriesForAccount, GetRepositoriesForAccountPayload } from "@codeflash-ai/common"
import { CacheContainer } from "node-ts-cache"
import { MemoryStorage } from "node-ts-cache-storage-memory"
import { dedup } from "@/lib/request-dedup"

const memoryCache = new CacheContainer(new MemoryStorage())

export async function getRepositoriesForAccountCached(
  payload: GetRepositoriesForAccountPayload,
): Promise<{
  repoIds: string[]
  repos: {
    id: string
    installation_id: number
    created_at: Date
    is_active: boolean
    github_repo_id: string
    name: string
    full_name: string
    is_private: boolean
    has_github_action: boolean
    last_optimized: Date | null
    optimizations_limit: number | null
    optimizations_used: number
    added_by: string | null
    organization_id: string | null
  }[]
}> {
  const cacheKey =
    "orgId" in payload ? `repositories_org_${payload.orgId}` : `repositories_user_${payload.userId}`

  return dedup(`repos:${cacheKey}`, async () => {
    const repoIdsCacheKey = `${cacheKey}_ids`

    const cachedRepos = await memoryCache.getItem<any>(cacheKey)
    const cachedRepoIds = await memoryCache.getItem<string[]>(repoIdsCacheKey)
    if (cachedRepos && cachedRepoIds) {
      return { repoIds: cachedRepoIds, repos: cachedRepos }
    }

    const result = await getRepositoriesForAccount(payload)
    const repoIds = result.map(r => r.id)

    await memoryCache.setItem(cacheKey, result, { ttl: 600 })
    await memoryCache.setItem(repoIdsCacheKey, repoIds, { ttl: 600 })

    return { repoIds, repos: result }
  })
}
