import { describe, expect, it } from 'vitest'
import { detectMimeFromMagicBytes } from './magic-bytes'
import { InvalidPresignKeyError, presignR2Put } from './presign-s3compat'

const CREDS = {
  endpoint: 'https://uploads.example.com',
  accessKeyId: 'test-access-key',
  secretAccessKey: 'test-secret-key',
  region: 'auto',
}

describe('@platform-modules/uploads/presign-s3compat', () => {
  it('emits a single-key PUT URL with bounded expiry and signed Content-Type', async () => {
    const key = 'users/u1/avatar.png'
    const expiresIn = 900
    const contentType = 'image/png'

    const presigned = await presignR2Put(CREDS, key, contentType, expiresIn)
    const url = new URL(presigned.url)

    expect(presigned.method).toBe('PUT')
    expect(url.pathname).toBe(`/${key}`)
    expect(url.searchParams.get('X-Amz-Expires')).toBe(String(expiresIn))

    const signedHeaders = (url.searchParams.get('X-Amz-SignedHeaders') ?? '')
      .split(';')
      .map((part) => part.trim().toLowerCase())
      .filter(Boolean)
    expect(signedHeaders).toContain('content-type')
    expect(presigned.headers['content-type']).toBe(contentType)
  })

  it('rejects prefix/wildcard keys', async () => {
    await expect(presignR2Put(CREDS, 'users/*', 'image/png', 60)).rejects.toBeInstanceOf(
      InvalidPresignKeyError,
    )
    await expect(presignR2Put(CREDS, 'users/u1/', 'image/png', 60)).rejects.toBeInstanceOf(
      InvalidPresignKeyError,
    )
  })

  it('documents post-upload trust: declared Content-Type is not byte validation', async () => {
    const jpegBytes = new Uint8Array([0xff, 0xd8, 0xff, 0xe0])
    const presigned = await presignR2Put(CREDS, 'obj.jpg', 'image/png', 120)
    expect(presigned.headers['content-type']).toBe('image/png')
    expect(detectMimeFromMagicBytes(jpegBytes)).toBe('image/jpeg')
  })
})
