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

export function findByCompany(companyId: string) {
  return prisma.rentalPayment.findMany({
    where: { companyId },
    include: { reservation: { include: { customer: true, vehicle: true } } },
    orderBy: { createdAt: 'desc' },
    take: 100,
  })
}

export function findByReservation(reservationId: string, companyId: string) {
  return prisma.rentalPayment.findMany({ where: { reservationId, companyId }, orderBy: { createdAt: 'desc' } })
}

export function findByAmanpay(transactionId: string) {
  return prisma.rentalPayment.findFirst({ where: { amanpayTransactionId: transactionId } })
}

export function findByPaypal(captureId: string) {
  return prisma.rentalPayment.findFirst({ where: { paypalCaptureId: captureId } })
}

export function findByPaypalForCompany(paypalOrderId: string, companyId: string) {
  return prisma.rentalPayment.findFirstOrThrow({ where: { paypalCaptureId: paypalOrderId, companyId } })
}

export function findPaymentOrThrow(paymentId: string, companyId: string, reservationId: string) {
  return prisma.rentalPayment.findFirstOrThrow({ where: { id: paymentId, companyId, reservationId } })
}

export function findReservationOrThrow(id: string, companyId: string) {
  return prisma.reservation.findFirstOrThrow({
    where: { id, companyId },
    include: { vehicle: true, customer: true, rentalPayments: true },
  })
}

export function findReservation(id: string, companyId: string) {
  return prisma.reservation.findFirstOrThrow({
    where: { id, companyId },
    include: { rentalPayments: true },
  })
}

export function markPaymentSucceeded(id: string) {
  return prisma.rentalPayment.update({ where: { id }, data: { status: 'SUCCEEDED', paidAt: new Date() } })
}

export function markPaymentFailed(query: { amanpayTransactionId?: string; paypalCaptureId?: string }) {
  return prisma.rentalPayment.updateMany({ where: query, data: { status: 'FAILED' } })
}

export function incrementReservationPaid(reservationId: string, _amount: number) {
  return prisma.$transaction(async (tx) => {
    const reservation = await tx.reservation.findUniqueOrThrow({
      where: { id: reservationId },
      include: {
        rentalPayments: {
          where: { type: 'CHARGE', status: 'SUCCEEDED' },
          select: { amount: true },
        },
      },
    })
    const paidAmount = reservation.rentalPayments.reduce((total, payment) => total + payment.amount, 0)
    return tx.reservation.update({
      where: { id: reservationId },
      data: {
        paidAmount,
        paymentStatus: paidAmount >= reservation.totalAmount ? 'PAID' : 'PARTIAL',
      },
    })
  })
}

export function createPayment(data: {
  companyId: string; reservationId: string; amount: number; currency: string
  status: string; type: string; paymentProvider: string
  amanpayTransactionId?: string | null; paypalCaptureId?: string | null; paymentMethod?: string; paidAt?: Date
}) {
  return prisma.rentalPayment.create({ data: data as any })
}

export function updatePaypalCapture(id: string, captureId: string) {
  return prisma.rentalPayment.update({ where: { id }, data: { status: 'SUCCEEDED', paidAt: new Date(), paypalCaptureId: captureId } })
}

export function setReservationPaidAmount(reservationId: string, paidAmount: number, paymentStatus: string) {
  return prisma.reservation.update({ where: { id: reservationId }, data: { paidAmount, paymentStatus: paymentStatus as any } })
}

export function setReservationRefunded(reservationId: string) {
  return prisma.reservation.update({ where: { id: reservationId }, data: { paymentStatus: 'REFUNDED' } })
}

export function setPaymentRefunded(id: string, partial: boolean) {
  return prisma.rentalPayment.update({ where: { id }, data: { status: partial ? 'PARTIALLY_REFUNDED' : 'REFUNDED' } })
}
