import { prisma } from '../lib/prisma'
import { LicenseStatus } from '@rentaldrivego/database'

const THREE_MONTHS_MS = 3 * 30 * 24 * 60 * 60 * 1000

export interface LicenseValidationResult {
  status: 'VALID' | 'EXPIRING' | 'EXPIRED'
  daysUntilExpiry: number | null
  requiresApproval: boolean
  message: string
}

export function validateLicense(licenseExpiry: Date | null): LicenseValidationResult {
  if (!licenseExpiry) {
    return { status: 'VALID', daysUntilExpiry: null, requiresApproval: false, message: 'No expiry date on record' }
  }

  const now = new Date()
  const daysUntilExpiry = Math.ceil((licenseExpiry.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))

  if (licenseExpiry <= now) {
    return { status: 'EXPIRED', daysUntilExpiry, requiresApproval: true, message: `License expired ${Math.abs(daysUntilExpiry)} day(s) ago` }
  }

  if (licenseExpiry.getTime() - now.getTime() < THREE_MONTHS_MS) {
    return { status: 'EXPIRING', daysUntilExpiry, requiresApproval: true, message: `License expires in ${daysUntilExpiry} day(s) — approval required` }
  }

  return { status: 'VALID', daysUntilExpiry, requiresApproval: false, message: `Valid — expires in ${daysUntilExpiry} day(s)` }
}

export async function validateAndFlagLicense(customerId: string) {
  const customer = await prisma.customer.findUniqueOrThrow({ where: { id: customerId } })
  const result = validateLicense(customer.licenseExpiry)

  const status: LicenseStatus =
    result.status === 'EXPIRED' ? 'EXPIRED' :
    result.status === 'EXPIRING' ? 'EXPIRING' : 'VALID'

  await prisma.customer.update({
    where: { id: customerId },
    data: {
      licenseExpired:          result.status === 'EXPIRED',
      licenseExpiringSoon:     result.status === 'EXPIRING',
      licenseValidationStatus: status,
      flagged:                 result.requiresApproval ? true : customer.flagged,
      flagReason:              result.requiresApproval ? result.message : customer.flagReason,
    },
  })

  return result
}
