import { legacyClient } from '../clients'

export type ListBlogItemType = {
  id: number
  title: string

  /** ISO8601 */
  created_at: Date

  /** ISO8601 */
  updated_at: Date

  featured_image: null | {
    image_url: string
  }

  author: {
    id: number
    username: string
    nickname: string
    avatar: {
      image_url: string
    }
  }
}

export type BlogContentType = ListBlogItemType & {
  content: string
}

export const listBlogs = async ({
  page = 1,
  limit = 20,
}: {
  page?: number
  limit?: number
}) => {
  const resp = await legacyClient.post('/v1/blog/list', { page, limit })
  return resp.data.data.map((blog: any) => {
    let _blog = blog
    if (blog.featured_image) {
      _blog = {
        ...blog,
        featured_image: {
          image_url:
            'https://legacy.passthem.top' + blog.featured_image.image_url,
        },
      }
    } else {
      _blog = blog
    }

    _blog.author.avatar = {
      image_url: 'https://legacy.passthem.top' + _blog.author.avatar.image_url,
    }
    _blog.created_at = new Date(_blog.created_at)
    _blog.updated_at = new Date(_blog.updated_at)

    return _blog
  }) as ListBlogItemType[]
}

export const getBlog: (
  blog_id: number,
) => Promise<null | BlogContentType> = async (blog_id: number) => {
  const resp = await legacyClient.get(`/v1/blog/${blog_id}`, {
    validateStatus: (status) => status == 200 || status == 404,
  })
  if (resp.status == 404) {
    return null
  }
  let _blog = resp.data

  if (_blog.featured_image) {
    _blog = {
      ..._blog,
      featured_image: {
        image_url:
          'https://legacy.passthem.top' + _blog.featured_image.image_url,
      },
    }
  }

  _blog.author.avatar = {
    image_url: 'https://legacy.passthem.top' + _blog.author.avatar.image_url,
  }
  _blog.created_at = new Date(_blog.created_at)
  _blog.updated_at = new Date(_blog.updated_at)

  return _blog
}
