import { prisma } from '../../lib/prisma'
import { uploadImage, deleteImage } from '../../lib/storage'
import { NotFoundError } from '../../http/errors'

export async function listPhotos(reservationId: string, companyId: string) {
  const reservation = await prisma.reservation.findFirst({ where: { id: reservationId, companyId }, select: { id: true } })
  if (!reservation) throw new NotFoundError('Reservation not found')
  return prisma.reservationPhoto.findMany({
    where: { reservationId },
    orderBy: { createdAt: 'asc' },
  })
}

export async function uploadPhoto(
  reservationId: string,
  companyId: string,
  type: 'PICKUP' | 'DROPOFF',
  buffer: Buffer,
) {
  const reservation = await prisma.reservation.findFirst({ where: { id: reservationId, companyId }, select: { id: true } })
  if (!reservation) throw new NotFoundError('Reservation not found')
  const url = await uploadImage(buffer, `companies/${companyId}/reservations/${reservationId}/photos`)
  return prisma.reservationPhoto.create({ data: { reservationId, type, url } })
}

export async function deletePhoto(photoId: string, reservationId: string, companyId: string) {
  const photo = await prisma.reservationPhoto.findFirst({
    where: { id: photoId, reservationId, reservation: { companyId } },
  })
  if (!photo) throw new NotFoundError('Photo not found')
  await deleteImage(photo.url)
  await prisma.reservationPhoto.delete({ where: { id: photoId } })
}
