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

import {
  crumbImageUrl,
  fetchRemoteImage,
  publicImageUrl,
} from './source-image'

describe('crumbImageUrl precedence', () => {
  const url = (ref: string) => publicImageUrl(ref)!

  test('manual crumb image wins over the source', () => {
    expect(
      crumbImageUrl(
        {imageRef: 'crumb-images/a.webp'},
        {
          imageRef: 'source-images/b.webp',
          assetRef: 'screengrabs/c.webp',
        },
      ),
    ).toBe(url('crumb-images/a.webp'))
  })

  test('falls back to the source display image', () => {
    expect(
      crumbImageUrl(
        {imageRef: null},
        {
          imageRef: 'source-images/b.webp',
          assetRef: 'screengrabs/c.webp',
        },
      ),
    ).toBe(url('source-images/b.webp'))
  })

  test('falls back to the source asset', () => {
    expect(
      crumbImageUrl(
        {imageRef: null},
        {imageRef: null, assetRef: 'screengrabs/c.webp'},
      ),
    ).toBe(url('screengrabs/c.webp'))
  })

  test('null when nothing is set', () => {
    expect(crumbImageUrl({imageRef: null}, null)).toBeNull()
    expect(
      crumbImageUrl(
        {imageRef: null},
        {imageRef: null, assetRef: null},
      ),
    ).toBeNull()
  })
})

describe('fetchRemoteImage is best-effort and ssrf-guarded', () => {
  test('returns null for private/loopback hosts', async () => {
    expect(
      await fetchRemoteImage('http://127.0.0.1/x.jpg'),
    ).toBeNull()
  })

  test('returns null for non-http urls', async () => {
    expect(
      await fetchRemoteImage('ftp://example.com/x.jpg'),
    ).toBeNull()
  })
})
