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

// Mock fetch globally
global.fetch = vi.fn()

describe('Image Uploads - Disabled Flag', () => {
  const originalEnv = { ...process.env }

  beforeEach(() => {
    resetFlagsCache()
    vi.clearAllMocks()

    // Set up agent but disable image uploads
    process.env.AGENT_1_URL = 'https://example.com/webhook/test'
    process.env.IMAGE_UPLOADS_ENABLED = 'false'
    process.env.DIFF_TOOL_ENABLED = 'true'
  })

  afterEach(() => {
    process.env = { ...originalEnv}
    resetFlagsCache()
  })

  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 currently disabled')
    expect(data.hint).toContain('IMAGE_UPLOADS_ENABLED')

    // Ensure webhook was never called
    expect(global.fetch).not.toHaveBeenCalled()
  })

  it('accepts requests without images when flag is disabled', async () => {
    const mockResponse = JSON.stringify({ response: 'Text only response' })

    ;(global.fetch as any).mockResolvedValueOnce({
      ok: true,
      status: 200,
      text: async () => mockResponse,
    })

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

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

    expect(response.status).toBe(200)
    expect(data.response).toBe('Text only response')
    expect(global.fetch).toHaveBeenCalled()
  })

  it('allows empty images array when flag is disabled', async () => {
    const mockResponse = JSON.stringify({ response: 'Success' })

    ;(global.fetch as any).mockResolvedValueOnce({
      ok: true,
      status: 200,
      text: async () => mockResponse,
    })

    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Text message',
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
        images: [], // Empty array is allowed
      }),
    })

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

    expect(response.status).toBe(200)
    expect(data.response).toBe('Success')
  })
})
