import {NextResponse} from 'next/server'
import DAL from '@dal'

import {validateSchema} from '@/lib/server/utils/actionUtils'
import {createContactSchema} from '@/lib/schemas/contactSchemas'
import {wrapper} from '@/lib/server/utils/apiWrapper'

export const GET = wrapper(async (request, {tokenBody}): Promise<NextResponse> => {
  const searchParams = request.nextUrl.searchParams
  const contactName = searchParams.get('name') ?? ''
  const contacts = await DAL.getContacts(tokenBody!.id, contactName)

  // 200 OK response
  return new NextResponse(JSON.stringify(contacts), {
    status: 200,
  })
})

export const POST = wrapper(async (request, {tokenBody}): Promise<NextResponse> => {
  const {errors, data} = validateSchema(createContactSchema, await request.json())

  if (errors) {
    // 400 Bad Request response
    return new NextResponse(JSON.stringify(errors), {
      status: 400,
    })
  }

  const newContact = await DAL.createContact(tokenBody!.id, data)

  // 200 OK response
  return new NextResponse(JSON.stringify(newContact), {
    status: 200,
  })
})
