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

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<{ url: string; data: IStoreItem }> {
  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, data } = await response.json()
  return {
    url: `/api/document/${id}`,
    data,
  }
}
