import { defineStore } from 'pinia'
import { ref } from 'vue'
import gitApi from '../api/git.api'
import { useLoadable } from '../composables/useLoadable'
import type { GiteaRepo, Commit } from '../lib/interfaces/git.interface'

export const useGitStore = defineStore('git', () => {
  const repos = ref<GiteaRepo[]>([])
  const commits = ref<Commit[]>([])
  const { loading, error, withCache, invalidate } = useLoadable()

  async function fetch() {
    await withCache(async () => {
      repos.value = await gitApi.repos()

      const commitPromises = repos.value.map(repo =>
        gitApi.commits(repo.owner.login, repo.name, repo.html_url)
      )

      const all = (await Promise.all(commitPromises)).flat()
      all.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
      commits.value = all.slice(0, 20)
    })
  }

  return { repos, commits, loading, error, fetch, invalidate }
})
