import { defineStore } from 'pinia'
import { ref } from 'vue'
import youtubeApi from '../api/youtube.api'
import { formatDateTime } from '../lib/dateFormat'
import { useLoadable } from '../composables/useLoadable'

export const useYoutubeStore = defineStore('youtube', () => {
  const { loading, error, withCache } = useLoadable(0)
  const noConfig = ref(false)
  const videoId = ref('')
  const title = ref('')
  const publishDate = ref('')
  const viewCount = ref('')

  function formatViews(n: number): string {
    if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M views'
    if (n >= 1_000) return Math.round(n / 1_000) + 'K views'
    return n + ' views'
  }

  async function fetch() {
    noConfig.value = false
    await withCache(async () => {
      const video = await youtubeApi.latestVideo()
      if (!video) {
        noConfig.value = true
        return
      }
      videoId.value = video.id
      title.value = video.title
      publishDate.value = formatDateTime(video.publishDate)
      viewCount.value = video.viewCount ? formatViews(Number(video.viewCount)) : ''
    })
  }

  return { loading, error, noConfig, videoId, title, publishDate, viewCount, fetch }
})
