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

export const useGitStore = defineStore('git', () => {
  const repos = ref<GiteaRepo[]>([])
  const commits = ref<Commit[]>([])
  const error = ref<string | null>(null)

  async function fetchAll() {
    try {
      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)
    } catch (e: any) {
      error.value = e.message
    }
  }

  return { repos, commits, error, fetchAll }
})
