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

const REVIEW_INCLUDE = {
  reservation: {
    select: {
      id: true,
      startDate: true,
      endDate: true,
      reviewToken: true,
      reviewRequestSentAt: true,
      reviewReminderSentAt: true,
      reviewFinalReminderSentAt: true,
      reviewPaused: true,
      customer: {
        select: {
          id: true,
          firstName: true,
          lastName: true,
          email: true,
          reviewOptOut: true,
        },
      },
      vehicle: {
        select: {
          id: true,
          make: true,
          model: true,
          year: true,
        },
      },
    },
  },
}

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

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

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

export async function getStats(companyId: string) {
  const reviews = await prisma.review.findMany({
    where: { companyId },
    select: { overallRating: true, vehicleRating: true, serviceRating: true },
  })

  const total = reviews.length
  const byRating: Record<number, number> = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }

  let sumOverall = 0
  let sumVehicle = 0
  let countVehicle = 0
  let sumService = 0
  let countService = 0

  for (const r of reviews) {
    sumOverall += r.overallRating
    byRating[r.overallRating] = (byRating[r.overallRating] ?? 0) + 1
    if (r.vehicleRating != null) { sumVehicle += r.vehicleRating; countVehicle++ }
    if (r.serviceRating != null) { sumService += r.serviceRating; countService++ }
  }

  return {
    total,
    averageOverall: total > 0 ? Math.round((sumOverall / total) * 10) / 10 : 0,
    averageVehicle: countVehicle > 0 ? Math.round((sumVehicle / countVehicle) * 10) / 10 : 0,
    averageService: countService > 0 ? Math.round((sumService / countService) * 10) / 10 : 0,
    byRating,
  }
}

export async function sendReminder(
  reservationId: string,
  sentAt: Date,
  field: 'reviewReminderSentAt' | 'reviewFinalReminderSentAt',
) {
  return prisma.reservation.update({
    where: { id: reservationId },
    data: { [field]: sentAt },
  })
}
