import { describe, it, expect, beforeEach, vi } from 'vitest'
import { POST } from '@/app/api/chat/route'
import { NextRequest } from 'next/server'
import { resetFlagsCache } from '@/lib/flags'

describe('/api/chat', () => {
  beforeEach(() => {
    resetFlagsCache()
    vi.clearAllMocks()
    process.env.IMAGE_UPLOADS_ENABLED = 'true'
    process.env.OPENROUTER_API_KEY = 'test-key'
    process.env.OPENROUTER_MODEL = 'openai/gpt-oss-120b'
  })

  it('requires message field', async () => {
    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
      }),
    })

    const response = await POST(request)
    const data = await response.json()

    expect(response.status).toBe(400)
    expect(data.error).toBe('Message is required')
  })

  it('requires agentId field', async () => {
    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Hello',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
      }),
    })

    const response = await POST(request)
    const data = await response.json()

    expect(response.status).toBe(400)
    expect(data.error).toBe('Agent ID is required')
  })

  it('rejects images when IMAGE_UPLOADS_ENABLED is false', async () => {
    process.env.IMAGE_UPLOADS_ENABLED = 'false'
    resetFlagsCache()

    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Hello',
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
        images: ['data:image/png;base64,abc123'],
      }),
    })

    const response = await POST(request)
    const data = await response.json()

    expect(response.status).toBe(403)
    expect(data.error).toBe('Image uploads are not enabled')
  })

  it('accepts valid chat request for standard agent', async () => {
    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Hello agent',
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
      }),
    })

    const response = await POST(request)

    // Should return 200
    expect(response.status).toBe(200)
  })

  it('accepts valid chat request for Morgan agent', async () => {
    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Create an agent',
        agentId: 'agent-2',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
      }),
    })

    const response = await POST(request)

    // Should return 200
    expect(response.status).toBe(200)
  })
})
