import { describe, it, expect, beforeAll } from 'vitest'
import {
  signExternalLunchToken,
  verifyExternalLunchToken,
} from '../../src/lib/external-lunch-token'

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

describe('external lunch token', () => {
  it('round-trips a payload', () => {
    const exp = Math.floor(Date.now() / 1000) + 86400
    const token = signExternalLunchToken({ externalId: 'cmx_test', exp })
    const verified = verifyExternalLunchToken(token)
    expect(verified.externalId).toBe('cmx_test')
    expect(verified.exp).toBe(exp)
  })

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

  it('rejects expired tokens', () => {
    const exp = Math.floor(Date.now() / 1000) - 1
    const token = signExternalLunchToken({ externalId: 'cmx_test', exp })
    expect(() => verifyExternalLunchToken(token)).toThrow(/expired/i)
  })

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