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

export function findMany(companyId: string, filters: { active?: string; public?: string }) {
  const where: any = { companyId }
  if (filters.active !== undefined) where.isActive = filters.active === 'true'
  if (filters.public !== undefined) where.isPublic = filters.public === 'true'
  return prisma.offer.findMany({ where, orderBy: { createdAt: 'desc' } })
}

export function findByIdOrThrow(id: string, companyId: string) {
  return prisma.offer.findFirstOrThrow({ where: { id, companyId }, include: { vehicles: true } })
}

export function findFirst(id: string, companyId: string) {
  return prisma.offer.findFirst({ where: { id, companyId } })
}

export async function create(companyId: string, data: any, vehicleIds: string[]) {
  return prisma.offer.create({
    data: {
      ...data,
      companyId,
      validFrom:  new Date(data.validFrom),
      validUntil: new Date(data.validUntil),
      vehicles: vehicleIds.length > 0 ? { create: vehicleIds.map((id) => ({ vehicleId: id })) } : undefined,
    },
    include: { vehicles: true },
  })
}

export async function update(id: string, data: any, vehicleIds?: string[]) {
  return prisma.$transaction(async (tx: any) => {
    await tx.offer.update({
      where: { id },
      data: {
        ...data,
        validFrom:  data.validFrom  ? new Date(data.validFrom)  : undefined,
        validUntil: data.validUntil ? new Date(data.validUntil) : undefined,
      },
    })
    if (vehicleIds !== undefined) {
      await tx.offerVehicle.deleteMany({ where: { offerId: id } })
      if (vehicleIds.length > 0) {
        await tx.offerVehicle.createMany({ data: vehicleIds.map((vehicleId) => ({ offerId: id, vehicleId })) })
      }
    }
    return tx.offer.findUniqueOrThrow({ where: { id }, include: { vehicles: true } })
  })
}

export function deleteMany(id: string, companyId: string) {
  return prisma.offer.deleteMany({ where: { id, companyId } })
}

export function setActive(id: string, companyId: string, isActive: boolean) {
  return prisma.offer.updateMany({ where: { id, companyId }, data: { isActive } })
}

export async function getStats(id: string, companyId: string) {
  const offer = await prisma.offer.findFirstOrThrow({ where: { id, companyId } })
  const reservations = await prisma.reservation.count({ where: { offerId: offer.id } })
  return { redemptions: offer.redemptionCount, reservations }
}
