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

import { createSignedPutUrl } from '../../../lib/portal-file-storage'
import { UploadContentRejectedError, validateUploadContent } from '../../../lib/upload-mime-guard'
import { guardMagicBytes, imageDimensions, presignPut } from '../uploads'

const PNG_2X3 = new Uint8Array([
  0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
  0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03,
])

const JPEG_4X5 = new Uint8Array([
  0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01,
  0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0xff, 0xc0, 0x00, 0x0b,
  0x08, 0x00, 0x05, 0x00, 0x04, 0x01, 0x01, 0x11, 0x00,
])

const PDF_HEADER = new TextEncoder().encode('%PDF-1.7\n')
const SVG_HEADER = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"></svg>')

const ENV = {
  STORAGE: {},
  CF_ACCOUNT_ID: 'acct',
  R2_ACCESS_KEY_ID: 'key',
  R2_SECRET_ACCESS_KEY: 'secret',
  R2_BUCKET_NAME: 'zync-storage',
}

function classifyWithLegacyGuard(mimeType: string, bytes: Uint8Array): { accepted: boolean } {
  try {
    validateUploadContent(mimeType, bytes)
    return { accepted: true }
  } catch (error) {
    if (error instanceof UploadContentRejectedError) {
      return { accepted: false }
    }
    throw error
  }
}

function pickComparableQuery(url: string): Record<string, string> {
  const parsed = new URL(url)
  const keys = [
    'X-Amz-Algorithm',
    'X-Amz-Credential',
    'X-Amz-Expires',
  ]
  return Object.fromEntries(keys.map((key) => [key, parsed.searchParams.get(key) ?? '']))
}

describe('platform uploads parity', () => {
  it('matches the legacy upload guard verdict on real headers', () => {
    const cases = [
      { mimeType: 'image/png', bytes: PNG_2X3 },
      { mimeType: 'image/jpeg', bytes: JPEG_4X5 },
      { mimeType: 'application/pdf', bytes: PDF_HEADER },
      { mimeType: 'image/svg+xml', bytes: SVG_HEADER },
    ]

    for (const testCase of cases) {
      expect(guardMagicBytes(testCase.mimeType, testCase.bytes)).toEqual(
        classifyWithLegacyGuard(testCase.mimeType, testCase.bytes),
      )
    }
  })

  it('parses real image dimensions from header bytes', () => {
    expect(imageDimensions(PNG_2X3)).toEqual({ width: 2, height: 3 })
    expect(imageDimensions(JPEG_4X5)).toEqual({ width: 4, height: 5 })
    expect(imageDimensions(PDF_HEADER)).toBeNull()
  })

  it('matches the legacy presign URL shape and signed params', async () => {
    const key = 'tenants/t1/logo.png'
    const contentType = 'image/png'
    const expiresIn = 300

    const legacyUrl = await createSignedPutUrl(ENV as never, key, {
      contentType,
      expiresIn,
    })
    const platformPresign = await presignPut(ENV as never, key, {
      contentType,
      expiresIn,
    })

    expect(platformPresign.method).toBe('PUT')
    expect(platformPresign.headers['content-type']).toBe(contentType)
    expect(new URL(platformPresign.url).pathname).toBe(new URL(legacyUrl).pathname)
    expect(pickComparableQuery(platformPresign.url)).toEqual(pickComparableQuery(legacyUrl))
    expect(new URL(legacyUrl).searchParams.get('X-Amz-SignedHeaders')).toBe('host')
    expect(new URL(platformPresign.url).searchParams.get('X-Amz-SignedHeaders')).toBe(
      'content-type;host',
    )
  })
})
