import { prisma } from '../lib/prisma'
import { resolveSettingsEntitlements } from '../modules/companies/settingsEntitlements'
import { validateLicense } from './licenseValidationService'

type AdditionalDriverCharge = 'PER_DAY' | 'FLAT' | 'FREE'

export interface AdditionalDriverInput {
  firstName: string
  lastName: string
  email?: string
  phone?: string
  driverLicense: string
  licenseExpiry?: string | null
  licenseIssuedAt?: string | null
  dateOfBirth?: string | null
  nationality?: string
}

export function calculateAdditionalDriverCharge(
  chargeType: AdditionalDriverCharge,
  chargeValue: number,
  totalDays: number,
) {
  switch (chargeType) {
    case 'PER_DAY':
      return chargeValue * totalDays
    case 'FLAT':
      return chargeValue
    default:
      return 0
  }
}

export async function applyAdditionalDriversToReservation(
  reservationId: string,
  companyId: string,
  drivers: AdditionalDriverInput[],
  totalDays: number,
) {
  if (drivers.length === 0) {
    return { records: [], additionalDriverTotal: 0, requiresManualApproval: false }
  }

  const entitlements = await resolveSettingsEntitlements(companyId)
  const canApplyAutomatedFees = entitlements.features['settings.additional_driver_fees']?.available
  const settings = canApplyAutomatedFees
    ? await prisma.contractSettings.findUnique({ where: { companyId } })
    : null
  const chargeType = settings?.additionalDriverCharge ?? 'FREE'
  const chargeValue =
    chargeType === 'PER_DAY'
      ? settings?.additionalDriverDailyRate ?? 0
      : chargeType === 'FLAT'
      ? settings?.additionalDriverFlatRate ?? 0
      : 0

  const records = drivers.map((driver) => {
    const licenseResult = validateLicense(driver.licenseExpiry ? new Date(driver.licenseExpiry) : null)
    const totalCharge = calculateAdditionalDriverCharge(chargeType, chargeValue, totalDays)

    return {
      reservationId,
      companyId,
      firstName: driver.firstName,
      lastName: driver.lastName,
      email: driver.email ?? null,
      phone: driver.phone ?? null,
      driverLicense: driver.driverLicense,
      licenseExpiry: driver.licenseExpiry ? new Date(driver.licenseExpiry) : null,
      licenseIssuedAt: driver.licenseIssuedAt ? new Date(driver.licenseIssuedAt) : null,
      dateOfBirth: driver.dateOfBirth ? new Date(driver.dateOfBirth) : null,
      nationality: driver.nationality ?? null,
      chargeType,
      chargeValue,
      totalCharge,
      licenseExpired: licenseResult.status === 'EXPIRED',
      licenseExpiringSoon: licenseResult.status === 'EXPIRING',
      requiresApproval: licenseResult.requiresApproval,
      approvalNote: licenseResult.requiresApproval ? licenseResult.message : null,
    }
  })

  const additionalDriverTotal = records.reduce((sum, record) => sum + record.totalCharge, 0)

  await prisma.$transaction([
    prisma.additionalDriver.createMany({ data: records }),
    prisma.reservation.update({
      where: { id: reservationId },
      data: {
        additionalDriverTotal,
        totalAmount: { increment: additionalDriverTotal },
      },
    }),
  ])

  return {
    records,
    additionalDriverTotal,
    requiresManualApproval: records.some((record) => record.requiresApproval),
  }
}
