import { apiDelete, apiGet, apiPost } from '@/lib/api'

import type { Post, PostTagChange } from '@/types'


export const fetchPosts = async (
    { tags, match, page, limit, cursor }: {
	tags:     string
	match:    'any' | 'all'
	page?:    number
	limit?:   number
	cursor?:  string }
): Promise<{
    posts:      Post[]
    count:      number
    nextCursor: string }> =>
	await apiGet ('/posts', { params: {
	    tags,
	    match,
	    ...(page && { page }),
	    ...(limit && { limit }),
	    ...(cursor && { cursor }) } })


export const fetchPost = async (id: string): Promise<Post> => await apiGet (`/posts/${ id }`)


export const fetchPostChanges = async (
    { id, page, limit }: {
	id?:    string
	page:   number
	limit:  number },
): Promise<{
    changes:  PostTagChange[]
    count:    number }> =>
	await apiGet ('/posts/changes', { params: { ...(id && { id }), page, limit } })


export const toggleViewedFlg = async (id: string, viewed: boolean): Promise<void> => {
  await (viewed ? apiPost : apiDelete) (`/posts/${ id }/viewed`)
}
