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

import {
    buildPostNewReviewPath,
    hasPostNewReviewState,
    isPostNewReviewPathWithinLimit,
    parsePostNewReviewUrls,
    postNewReviewPathByteLength,
} from '@/lib/postNewQueryState'

describe ('post new review URL state', () => {
  it ('encodes each URL separately and preserves literal plus signs', () => {
    const urls = [
	'https://example.com/one+a',
	'https://example.com/two?value=b+c']

    const path = buildPostNewReviewPath (urls)

    expect (path).toBe (
	'/posts/new?urls=https%3A%2F%2Fexample.com%2Fone%2Ba'
	+ '+https%3A%2F%2Fexample.com%2Ftwo%3Fvalue%3Db%2Bc')
    expect (parsePostNewReviewUrls (path.slice ('/posts/new'.length))).toEqual (urls)
  })

  it ('uses only the raw urls parameter as review state', () => {
    expect (hasPostNewReviewState ('?session_id=old&meta=old')).toBe (false)
    expect (hasPostNewReviewState ('?unknown=value&urls=')).toBe (true)
    expect (parsePostNewReviewUrls ('?unknown=value&urls=one+two&meta=old'))
	.toEqual (['one', 'two'])
  })

  it ('allows at most a 6 143 byte request target', () => {
    const baseUrl = 'https://example.com/'
    const baseLength = postNewReviewPathByteLength ([baseUrl])
    const allowed = `${ baseUrl }${ 'a'.repeat (6_143 - baseLength) }`
    const denied = `${ allowed }a`

    expect (postNewReviewPathByteLength ([allowed])).toBe (6_143)
    expect (isPostNewReviewPathWithinLimit ([allowed])).toBe (true)
    expect (postNewReviewPathByteLength ([denied])).toBe (6_144)
    expect (isPostNewReviewPathWithinLimit ([denied])).toBe (false)
  })
})
