import { apiGet } from '@/lib/api'

import type { Deerjikist,
	      FetchNicoTagsParams,
	      FetchTagsParams,
	      NicoTag,
	      Tag,
	      TagVersion } from '@/types'


export const fetchTags = async (
    { post, name, category, postCountGTE, postCountLTE, createdFrom, createdTo,
      updatedFrom, updatedTo, deprecated,
      page, limit, order }: FetchTagsParams): Promise<{ tags:  Tag[]
	     count: number }> =>
    await apiGet ('/tags', { params: {
	...(post != null && { post }),
	...(name && { name }),
	...(category && { category }),
	...(postCountGTE != null && { post_count_gte: postCountGTE }),
	...(postCountLTE != null && { post_count_lte: postCountLTE }),
	...(createdFrom && { created_from: createdFrom }),
	...(createdTo && { created_to: createdTo }),
	...(updatedFrom && { updated_from: updatedFrom }),
	...(updatedTo && { updated_to: updatedTo }),
	...(deprecated != null && { deprecated: deprecated ? '1' : '0' }),
	...(page && { page }),
	...(limit && { limit }),
	...(order && { order }) } })


export const fetchNicoTags = async (
    { name, linkedTag, linkStatus, page, limit, order }: FetchNicoTagsParams): Promise<{ tags:  NicoTag[]
	     count: number }> =>
    await apiGet ('/tags/nico', { params: {
	page,
	limit,
	name,
	linked_tag:  linkedTag,
	link_status: linkStatus === 'all' ? '' : linkStatus,
	order } })


export const fetchTag = async (id: string): Promise<Tag | null> => {
  try
  {
    return await apiGet (`/tags/${ id }`)
  }
  catch
  {
    return null
  }
}


export const fetchTagByName = async (name: string): Promise<Tag | null> => {
  try
  {
    return await apiGet (`/tags/name/${ name }`)
  }
  catch
  {
    return null
  }
}

export const fetchTagChanges = async (
    { id, page, limit }: {
	id?:    string
	page:   number
	limit:  number }): Promise<{
    versions: TagVersion[]
    count:    number }> =>
	await apiGet ('/tags/versions', { params: { ...(id && { id }), page, limit } })


export const fetchDeerjikistsByTag = async (
    id: string): Promise<{ tag: Tag; deerjikists: Deerjikist[] }> =>
    await apiGet (`/tags/${ id }/deerjikists`)
