const qs = require('./lib-qs')

import Day from './repo-hunt-store-day'
import Repo from './repo-hunt-store-repo'

const handler = async request => {
  try {
    const body = await request.text()

    if (!body) {
      throw new Error('Incorrect data')
    }

    const data = qs.parse(body)
    console.log(`repo data:${JSON.stringify(data)}`)

    const repo = new Repo(data)
    console.log(`repo: ${JSON.stringify(repo)}`)
    await repo.save()
    await Day.add(repo.id)

    return new Response('ok', { headers: { Location: '/repo-hunt' }, status: 301 })
  } catch (err) {
    return new Response(err.toString(), { status: 400 })
  }
}

export default handler