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 {getSessionProfileFromCookie} from '@/lib/sessionUtils'

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

export async function GET(_request: NextRequest, {params}: RouteParams): Promise<NextResponse> {
  const {contactId} = await params
  const profile = await getSessionProfileFromCookie()

  if (!profile) {
    return unauthorized()
  }

  const contact = await getContact(contactId, profile.id)
  return ok(contact)
}

export async function PUT(request: NextRequest, {params}: RouteParams): Promise<NextResponse> {
  const {contactId} = await params
  const data = (await request.json()) as UpdateContactParams
  const updatedContact = await updateContact({...data, id: contactId})
  return ok(updatedContact)
}

export async function DELETE(_request: NextRequest, {params}: RouteParams): Promise<NextResponse> {
  const {contactId} = await params
  const profile = await getSessionProfileFromCookie()

  if (!profile) {
    return unauthorized()
  }

  await deleteContact(contactId, profile.id)
  return ok()
}
