import { describe, it, expect, beforeAll } from 'vitest'
import { signFinalistToken, verifyFinalistToken } from '../../src/lib/finalist-token'

beforeAll(() => {
  process.env.NEXTAUTH_SECRET = 'test-secret-for-finalist-tokens'
})

describe('finalist token', () => {
  it('round-trips a payload', () => {
    const exp = Math.floor(Date.now() / 1000) + 86400
    const token = signFinalistToken({ confirmationId: 'cmf_test', exp })
    const verified = verifyFinalistToken(token)
    expect(verified.confirmationId).toBe('cmf_test')
    expect(verified.exp).toBe(exp)
  })

  it('rejects tampered tokens', () => {
    const exp = Math.floor(Date.now() / 1000) + 86400
    const token = signFinalistToken({ confirmationId: 'cmf_test', exp })
    const tampered = token.slice(0, -2) + 'xx'
    expect(() => verifyFinalistToken(tampered)).toThrow(/signature/i)
  })

  it('rejects expired tokens', () => {
    const exp = Math.floor(Date.now() / 1000) - 1
    const token = signFinalistToken({ confirmationId: 'cmf_test', exp })
    expect(() => verifyFinalistToken(token)).toThrow(/expired/i)
  })

  it('rejects malformed tokens', () => {
    expect(() => verifyFinalistToken('not-a-token')).toThrow(/malformed/i)
  })
})
