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

import type { FetchPostsParams, Post, PostVersion } from '@/types'


export const fetchPosts = async (
    { url, title, tags, match, createdFrom, createdTo, updatedFrom, updatedTo,
      originalCreatedFrom, originalCreatedTo, page, limit, order }: FetchPostsParams): Promise<{
    posts:  Post[]
    count:  number }> =>
	await apiGet ('/posts', { params: {
	    ...(url && { url }),
	    ...(title && { title }),
	    ...(tags && { tags }),
	    ...(match && { match }),
	    ...(createdFrom && { created_from: createdFrom }),
	    ...(createdTo && { created_to: createdTo }),
	    ...(updatedFrom && { updated_from: updatedFrom }),
	    ...(updatedTo && { updated_to: updatedTo }),
	    ...(originalCreatedFrom && { original_created_from: originalCreatedFrom }),
	    ...(originalCreatedTo && { original_created_to: originalCreatedTo }),
	    ...(page && { page }),
	    ...(limit && { limit }),
	    ...(order && { order }) } })


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


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


export const updatePost = async (
    post: { id:                     number
	    title:                  string | null
	    tags:                   string
	    duration:               string | null
	    parentPostIds:          string
	    originalCreatedFrom:    string | null
	    originalCreatedBefore:  string | null },
    { baseVersionNo, force, merge }: {
	baseVersionNo?: number
	force?:         boolean
	merge?:         boolean }) =>
    await apiPut<Post> (
	`/posts/${ post.id }`,
	{ title: post.title,
	  tags: post.tags,
	  duration: post.duration,
	  parent_post_ids: post.parentPostIds,
	  original_created_from: post.originalCreatedFrom,
	  original_created_before: post.originalCreatedBefore },
	{ params: { ...(baseVersionNo && { base_version_no: String (baseVersionNo) }),
	            force: force ? '1' : '0',
		    merge: merge ? '1' : '0' } })


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