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('Image Uploads - Disabled Flag', () => {
  beforeEach(() => {
    resetFlagsCache()
    vi.clearAllMocks()
    process.env.IMAGE_UPLOADS_ENABLED = 'false'
    process.env.OPENROUTER_API_KEY = 'test-key'
    process.env.OPENROUTER_MODEL = 'openai/gpt-oss-120b'
  })

  it('rejects requests with images when flag is disabled', async () => {
    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Here is an image',
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
        images: ['data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='],
      }),
    })

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

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

  it('accepts requests without images when flag is disabled', async () => {
    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Text only',
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
      }),
    })

    const response = await POST(request)

    // Should succeed (streaming or plain, depending on setup)
    expect(response.status).toBe(200)
  })

  it('allows empty images array when flag is disabled', async () => {
    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Text with empty images',
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
        images: [],
      }),
    })

    const response = await POST(request)

    // Empty images array should be allowed
    expect(response.status).toBe(200)
  })
})
