import 'server-only'
import {Prisma} from '@prisma/client'
import {prismaClient} from './utils/prismaClient'
import {ContactWithInfoObject} from '@/lib/models/contacts'

export async function createContact(
  userId: string,
  contact: Prisma.ContactCreateWithoutUserInput,
): Promise<ContactWithInfoObject> {
  const newContact = await prismaClient.contact.create({data: {...contact, user: {connect: {id: userId}}}})
  return newContact as ContactWithInfoObject
}

export async function getContacts(userId: string, contactName: string): Promise<ContactWithInfoObject[]> {
  await new Promise(resolve => setTimeout(resolve, 1000))

  const contacts = await prismaClient.contact.findMany({
    where: {
      userId,
      OR: [
        {firstName: {contains: contactName, mode: 'insensitive'}},
        {lastName: {contains: contactName, mode: 'insensitive'}},
      ],
    },
  })
  return contacts as ContactWithInfoObject[]
}

export async function getContact(userId: string, id: string): Promise<ContactWithInfoObject> {
  // De findUnique methode geeft een null terug als er geen match gevonden is.
  // De findUniqueOrThrow methode gooit een error als er geen match gevonden is.
  const contact = await prismaClient.contact.findUniqueOrThrow({where: {id, userId}})
  return contact as ContactWithInfoObject
}

/**
 * Update an existing contact.
 *
 * @param userId
 * @param contact The updated contact info.
 */
export async function updateContact(
  userId: string,
  contact: Prisma.ContactUpdateInput & {id: string},
): Promise<ContactWithInfoObject> {
  const updatedContact = await prismaClient.contact.update({where: {id: contact.id, userId}, data: contact})
  return updatedContact as ContactWithInfoObject
}

/**
 * Delete an existing contact.
 *
 * @param userId
 * @param id The id of the contact to delete.
 */
export async function deleteContact(userId: string, id: string): Promise<void> {
  await prismaClient.contact.delete({where: {id, userId}})
}
