/**
 * Tests fuer die Advisor-RAG-Suche (ai-sdk, bge-m3).
 */

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

const mockFetch = vi.fn()
vi.stubGlobal('fetch', mockFetch)

describe('advisor-rag', () => {
  let mod: typeof import('../advisor-rag')

  beforeEach(async () => {
    vi.resetModules()
    mockFetch.mockReset()
    mod = await import('../advisor-rag')
  })

  describe('mapSdkResults', () => {
    it('mappt ai-sdk-Felder auf {content, source, score}', () => {
      const out = mod.mapSdkResults([
        { text: 'Art. 35 DSGVO ...', regulation_short: 'DSGVO', score: 0.91 },
      ])
      expect(out).toEqual([{ content: 'Art. 35 DSGVO ...', source: 'DSGVO', score: 0.91 }])
    })

    it('haengt article/paragraph an die Quelle an (Fallback ohne article_label)', () => {
      const out = mod.mapSdkResults([
        { text: 'Pflicht zur Benennung ...', regulation_short: 'BDSG', article: '§ 38', paragraph: '(1)', score: 0.8 },
      ])
      expect(out).toEqual([{ content: 'Pflicht zur Benennung ...', source: 'BDSG § 38 (1)', score: 0.8 }])
    })

    it('nutzt article_label direkt, wenn vorhanden (druckbare Fundstelle)', () => {
      const out = mod.mapSdkResults([
        { text: 'x', regulation_short: 'BDSG', article: '38', paragraph: '1', sub: 'Satz 2', article_label: 'BDSG § 38 Abs. 1', score: 0.9 },
      ])
      expect(out[0].source).toBe('BDSG § 38 Abs. 1')
    })

    it('faellt auf regulation_name/code zurueck und filtert leere Inhalte', () => {
      const out = mod.mapSdkResults([
        { text: '', regulation_short: 'X' },
        { text: 'Inhalt', regulation_name: 'BDSG' },
        { text: 'Inhalt2', regulation_code: 'EU_2016_679' },
      ])
      expect(out).toEqual([
        { content: 'Inhalt', source: 'BDSG', score: 0 },
        { content: 'Inhalt2', source: 'EU_2016_679', score: 0 },
      ])
    })
  })

  describe('queryAdvisorRAG (Authority Router)', () => {
    it('ruft den Router EINMAL auf und formatiert die Treffer', async () => {
      mockFetch.mockResolvedValue({
        ok: true,
        json: async () => ({ results: [{ text: 'Inhalt A', regulation_short: 'DSGVO', score: 0.9 }] }),
      })
      const result = await mod.queryAdvisorRAG('Was ist eine DSFA?')
      expect(result).toContain('[Quelle 1: DSGVO]')
      expect(result).toContain('Inhalt A')
      expect(mockFetch).toHaveBeenCalledTimes(1)
    })

    it('ruft /sdk/v1/rag/retrieve mit query + top_k (ohne collection) auf', async () => {
      mockFetch.mockResolvedValue({ ok: true, json: async () => ({ results: [] }) })
      await mod.queryAdvisorRAG('test')
      expect(mockFetch).toHaveBeenCalledWith(
        expect.stringContaining('/sdk/v1/rag/retrieve'),
        expect.objectContaining({ method: 'POST' }),
      )
      const body = JSON.parse(mockFetch.mock.calls[0][1].body)
      expect(body).toMatchObject({ query: 'test', top_k: 8 })
      expect(body.collection).toBeUndefined()
    })

    it('liefert leeren String wenn das RAG-Backend nicht erreichbar ist (graceful)', async () => {
      mockFetch.mockRejectedValue(new Error('connection refused'))
      const result = await mod.queryAdvisorRAG('test')
      expect(result).toBe('')
    })
  })
})
