import {TagCountSchema, type TagCount} from '@crumbs/core/schemas'

import {createSlotStore, slotHooks} from '@/lib/async-slot'
import {unwrap} from '@/lib/errors'
import {rpc} from '@/lib/rpc'
import {fromSchema} from '@/lib/snapshot-cache'
import {listSnapshot} from '@/lib/snapshots'

export type {TagCount}

const useTagsStore = createSlotStore<TagCount[]>(
  [],
  async () => {
    const {tags} = await unwrap(rpc.crumbs.tags.$get())
    return tags
  },
  listSnapshot('tags', 1, fromSchema(TagCountSchema)),
)

export const {useData: useTags, useRefresh: useRefreshTags} =
  slotHooks(useTagsStore)
