import {expect, test} from 'bun:test'

import {resolveClientIp} from './rate-limit'

test('ignores xff when proxy is not trusted', () => {
  expect(
    resolveClientIp({
      xff: '1.2.3.4',
      socketIp: '10.0.0.1',
      trustProxy: false,
    }),
  ).toBe('10.0.0.1')
})

test('uses last xff hop when proxy is trusted', () => {
  expect(
    resolveClientIp({
      xff: '1.2.3.4, 5.6.7.8',
      socketIp: '127.0.0.1',
      trustProxy: true,
    }),
  ).toBe('5.6.7.8')
})

test('falls back to socket ip when trusted but xff missing', () => {
  expect(
    resolveClientIp({
      xff: undefined,
      socketIp: '10.0.0.2',
      trustProxy: true,
    }),
  ).toBe('10.0.0.2')
})

test('returns null without xff or socket ip', () => {
  expect(
    resolveClientIp({
      xff: undefined,
      socketIp: null,
      trustProxy: false,
    }),
  ).toBeNull()
})

test('handles empty and padded xff entries', () => {
  expect(
    resolveClientIp({
      xff: ' 1.2.3.4 , , 9.9.9.9 ,',
      socketIp: null,
      trustProxy: true,
    }),
  ).toBe('9.9.9.9')
})
