import { getProtectedCustomerLicenseImageUrl } from '../../lib/storage'

export function parseReservationExtras(extras: unknown): Record<string, unknown> {
  if (!extras || typeof extras !== 'object' || Array.isArray(extras)) return {}
  return { ...(extras as Record<string, unknown>) }
}

export function normalizeOptionalString(value: string | null | undefined): string | null {
  const trimmed = typeof value === 'string' ? value.trim() : value
  return trimmed || null
}

export function buildReservationWorkflow(reservation: {
  status: string
  contractNumber: string | null
  invoiceNumber: string | null
  extras: unknown
}) {
  const extras = parseReservationExtras(reservation.extras)
  const closedAt = typeof extras.reservationClosedAt === 'string' ? extras.reservationClosedAt : null
  const contractGenerated = Boolean(reservation.contractNumber || reservation.invoiceNumber)
  const closed = Boolean(closedAt)

  return {
    contractGenerated,
    closed,
    closedAt,
    closedBy: typeof extras.reservationClosedBy === 'string' ? extras.reservationClosedBy : null,
    coreEditable: !closed && !contractGenerated && ['DRAFT', 'CONFIRMED'].includes(reservation.status),
    returnEditable: !closed && reservation.status === 'COMPLETED',
    checkInInspectionEditable: !closed && ['CONFIRMED', 'ACTIVE'].includes(reservation.status),
    checkOutInspectionEditable: !closed && reservation.status === 'COMPLETED',
  }
}

export function serializeReservationForDashboard<T extends {
  extras: unknown
  status: string
  contractNumber: string | null
  invoiceNumber: string | null
  customer?: {
    id: string
    licenseImageUrl?: string | null
  } | null
}>(reservation: T): T & { paymentMode: string | null; workflow: ReturnType<typeof buildReservationWorkflow> } {
  const extras = parseReservationExtras(reservation.extras)
  const customer =
    reservation.customer
      ? {
          ...reservation.customer,
          licenseImageUrl: reservation.customer.licenseImageUrl
            ? getProtectedCustomerLicenseImageUrl(reservation.customer.id)
            : null,
        }
      : reservation.customer

  return {
    ...reservation,
    ...(customer !== undefined ? { customer } : {}),
    paymentMode: typeof extras.paymentMode === 'string' ? extras.paymentMode : null,
    workflow: buildReservationWorkflow(reservation),
  }
}
