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) {
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(state),
  }

  const response = await fetch('/api/pdf/generate/brief', options)
  checkStatus(response)
  return response.json()
}

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

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