import type {NextRequest, NextResponse} from 'next/server'
import type {UpdateContactParams} from '@/dal/contacts'
import {deleteContact} from '@/dal/contacts'
import {getContact, updateContact} from '@/dal/contacts'
import {ok, unauthorized} from '@/lib/routeResponses'
import {validateJwtToken} from '@/lib/jwtUtils'

interface RouteParams {
  params: Promise<{contactId: string}>
}

export async function GET(request: NextRequest, {params}: RouteParams): Promise<NextResponse> {
  const [_, token] = (request.headers.get('Authorization') || ' ').split(' ')
  const tokenBody = validateJwtToken(token)
  if (!tokenBody) return unauthorized()

  const {contactId} = await params
  const contact = await getContact(contactId, tokenBody.id)
  return ok(contact)
}

export async function PUT(request: NextRequest, {params}: RouteParams): Promise<NextResponse> {
  const [_, token] = (request.headers.get('Authorization') || ' ').split(' ')
  const tokenBody = validateJwtToken(token)
  if (!tokenBody) return unauthorized()

  const {contactId} = await params
  const data = (await request.json()) as UpdateContactParams
  const updatedContact = await updateContact({...data, userId: tokenBody.id, id: contactId})
  return ok(updatedContact)
}

export async function DELETE(request: NextRequest, {params}: RouteParams): Promise<NextResponse> {
  const [_, token] = (request.headers.get('Authorization') || ' ').split(' ')
  const tokenBody = validateJwtToken(token)
  if (!tokenBody) return unauthorized()

  const {contactId} = await params
  await deleteContact(contactId, tokenBody.id)
  return ok()
}
