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

import { createSessionRoute } from './session.js'

describe('createSessionRoute', () => {
  it('exchanges valid credentials for an HttpOnly session cookie', async () => {
    const route = createSessionRoute({
      authEngine: {
        signIn: async () => ({
          principal: { userId: 'user-1', sessionId: 'session-1', roles: ['admin'] },
          accessToken: 'access-token',
          refreshToken: 'refresh-token',
        }),
      },
    })

    const response = await route.request('https://press-zone.test/session', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ email: 'admin@press.zone', password: 'correct-password' }),
    })

    expect(response.status).toBe(200)
    expect(await response.json()).toEqual({ data: { userId: 'user-1', roles: ['admin'] } })
    expect(response.headers.get('set-cookie')).toContain('access_token=access-token')
    expect(response.headers.get('set-cookie')).toContain('HttpOnly')
    expect(response.headers.get('set-cookie')).toContain('Secure')
    expect(response.headers.get('set-cookie')).toContain('SameSite=Lax')
  })

  it('returns generic unauthorized response when credentials are invalid', async () => {
    const route = createSessionRoute({
      authEngine: {
        signIn: async () => {
          throw new Error('invalid credentials')
        },
      },
    })

    const response = await route.request('https://press-zone.test/session', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ email: 'admin@press.zone', password: 'wrong-password' }),
    })

    expect(response.status).toBe(401)
    await expect(response.json()).resolves.toEqual({
      error: { code: 'UNAUTHORIZED', message: 'Invalid email or password' },
    })
  })
})
