import { NotFoundError, AppError } from '../../http/errors'
import { sendTransactionalEmail } from '../../services/notificationService'
import { reviewRequestEmail, type Lang } from '../../lib/emailTranslations'
import * as repo from './review.repo'
import * as reservationRepo from '../reservations/reservation.repo'

export async function listReviews(
  companyId: string,
  query: { rating?: number; page: number; pageSize: number },
) {
  const { rating, page, pageSize } = query
  const where: Record<string, unknown> = {}
  if (rating != null) where.overallRating = rating

  const [reviews, total] = await repo.findMany(companyId, where, (page - 1) * pageSize, pageSize)
  return {
    data: reviews,
    meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) },
  }
}

export async function getReview(id: string, companyId: string) {
  const review = await repo.findById(id, companyId)
  if (!review) throw new NotFoundError('Review not found')
  return review
}

export async function replyToReview(id: string, companyId: string, companyReply: string) {
  const review = await repo.findById(id, companyId)
  if (!review) throw new NotFoundError('Review not found')

  return repo.updateById(id, {
    companyReply,
    companyRepliedAt: new Date(),
  })
}

export async function getStats(companyId: string) {
  return repo.getStats(companyId)
}

export async function sendReviewReminder(id: string, companyId: string) {
  const review = await repo.findById(id, companyId)
  if (!review) throw new NotFoundError('Review not found')

  const reservation = review.reservation as any
  if (!reservation) throw new AppError('Review has no linked reservation', 400, 'no_reservation')
  if (reservation.reviewPaused) throw new AppError('Review requests are paused for this reservation', 400, 'review_paused')

  const customer = reservation.customer
  if (!customer || customer.reviewOptOut) throw new AppError('Customer has opted out of review requests', 400, 'opted_out')
  if (!customer.email) throw new AppError('Customer has no email address', 400, 'no_email')
  if (!reservation.reviewToken) throw new AppError('No review token available for this reservation', 400, 'no_token')

  // Determine which reminder field to update
  const field: 'reviewReminderSentAt' | 'reviewFinalReminderSentAt' =
    reservation.reviewReminderSentAt ? 'reviewFinalReminderSentAt' : 'reviewReminderSentAt'

  const company = await reservationRepo.findCompanyWithBrand(companyId)
  const lang = (company?.brand?.defaultLocale ?? 'fr') as Lang
  const companyName = company?.brand?.displayName ?? company?.name ?? 'the rental company'
  const vehicle = reservation.vehicle
  const vehicleLabel = vehicle ? `${vehicle.year} ${vehicle.make} ${vehicle.model}` : 'your rental vehicle'
  const reviewUrl = `${process.env.CARPLACE_URL ?? 'http://localhost:3000'}/review?token=${reservation.reviewToken}`

  await sendTransactionalEmail({
    to: customer.email,
    subject: reviewRequestEmail.subject(vehicleLabel, lang),
    html: reviewRequestEmail.html({ firstName: customer.firstName, companyName, vehicleLabel, reviewUrl }, lang),
    text: reviewRequestEmail.text({ firstName: customer.firstName, companyName, vehicleLabel, reviewUrl }, lang),
  })

  await repo.sendReminder(reservation.id, new Date(), field)

  return { success: true, field }
}
