import { beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('../../services/additionalDriverService', () => ({
  applyAdditionalDriversToReservation: vi.fn(),
  calculateAdditionalDriverCharge: vi.fn(),
}))

vi.mock('./reservation.repo', () => ({
  findAdditionalDriver: vi.fn(),
  updateAdditionalDriver: vi.fn(),
}))

import * as repo from './reservation.repo'
import { approveAdditionalDriver } from './reservation.additional-driver.service'

describe('reservation.additional-driver.service', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    vi.setSystemTime(new Date('2026-06-09T12:00:00.000Z'))
  })

  it('records manager approval metadata when an additional driver is approved', async () => {
    vi.mocked(repo.findAdditionalDriver).mockResolvedValue({ id: 'driver_1', approvalNote: 'License expiring' } as never)
    vi.mocked(repo.updateAdditionalDriver).mockResolvedValue({ id: 'driver_1', approvedBy: 'manager_1' } as never)

    await approveAdditionalDriver('reservation_1', 'driver_1', 'company_1', true, 'Approved after review', 'manager_1')

    expect(repo.findAdditionalDriver).toHaveBeenCalledWith('driver_1', 'reservation_1', 'company_1')
    expect(repo.updateAdditionalDriver).toHaveBeenCalledWith('driver_1', {
      approvedAt: new Date('2026-06-09T12:00:00.000Z'),
      approvedBy: 'manager_1',
      approvalNote: 'Approved after review',
    })
  })

  it('clears approval metadata on rejection while preserving the prior note if no new note is supplied', async () => {
    vi.mocked(repo.findAdditionalDriver).mockResolvedValue({ id: 'driver_1', approvalNote: 'Manual review needed' } as never)

    await approveAdditionalDriver('reservation_1', 'driver_1', 'company_1', false, undefined, 'manager_1')

    expect(repo.updateAdditionalDriver).toHaveBeenCalledWith('driver_1', {
      approvedAt: null,
      approvedBy: null,
      approvalNote: 'Manual review needed',
    })
  })
})
