import { IDocProps } from '../interfaces/IDocProps'
import { ILatest } from '../interfaces/ILatest'

function checkStatus(res: Response) {
  if (res.status < 200 || res.status >= 400) {
    throw new Error(`Something went wrong (Status ${res.status}) - I do feel very sorry!`)
  }
}

export async function generatePdf(state: IDocProps): Promise<string> {
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(state),
  }

  const response = await fetch('/api/document?template=brief', options)
  checkStatus(response)
  const { id } = await response.json()
  return `/api/document/${id}`
}

export async function getLatest(): Promise<ILatest[]> {
  const response = await fetch('/api/document/latest')
  checkStatus(response)
  return response.json()
}

export async function removeLatest(item: { id: string }) {
  const response = await fetch(`/api/document/${item.id}`, { method: 'DELETE' })
  checkStatus(response)
  return response
}
