import { prisma } from '../../lib/prisma'

const COMPLAINT_INCLUDE = {
  reservation: {
    select: {
      id: true,
      startDate: true,
      endDate: true,
      status: true,
      vehicle: { select: { make: true, model: true, year: true } },
    },
  },
  customer: {
    select: {
      id: true,
      firstName: true,
      lastName: true,
      email: true,
      phone: true,
    },
  },
  review: {
    select: {
      id: true,
      overallRating: true,
      comment: true,
    },
  },
}

export async function findMany(
  companyId: string,
  where: Record<string, unknown>,
  skip: number,
  take: number,
) {
  const baseWhere = { companyId, ...where }
  return Promise.all([
    prisma.complaint.findMany({
      where: baseWhere,
      include: COMPLAINT_INCLUDE,
      skip,
      take,
      orderBy: { createdAt: 'desc' },
    }),
    prisma.complaint.count({ where: baseWhere }),
  ])
}

export async function findById(id: string, companyId: string) {
  return prisma.complaint.findFirst({
    where: { id, companyId },
    include: COMPLAINT_INCLUDE,
  })
}

export async function create(data: {
  companyId: string
  reservationId?: string
  reviewId?: string
  customerId?: string
  severity: string
  category: string
  subject: string
  description?: string
  assignedTo?: string
}) {
  return prisma.complaint.create({
    data: data as any,
    include: COMPLAINT_INCLUDE,
  })
}

export async function updateById(id: string, data: Record<string, unknown>) {
  return prisma.complaint.update({
    where: { id },
    data,
    include: COMPLAINT_INCLUDE,
  })
}

export async function deleteById(id: string) {
  return prisma.complaint.delete({ where: { id } })
}
