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

// jsdom doesn't define window.location.origin — stub it
Object.defineProperty(window, 'location', {
  value: { origin: 'https://localhost' },
  writable: true,
})

describe('searchTemplates', () => {
  beforeEach(() => {
    vi.restoreAllMocks()
  })

  it('gibt Ergebnisse zurück wenn eigenes Backend verfügbar', async () => {
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
      ok: true,
      json: () => Promise.resolve({
        templates: [{
          id: 't1',
          title: 'Datenschutzerklärung (DSGVO-konform)',
          document_type: 'privacy_policy',
          content: '# Datenschutzerklärung\n\n{{COMPANY_NAME}}',
          description: 'Vollständige DSE',
          language: 'de',
          jurisdiction: 'DE',
          license_id: 'mit',
          license_name: 'MIT License',
          source_name: 'BreakPilot Compliance',
          attribution_required: false,
          is_complete_document: true,
          placeholders: ['{{COMPANY_NAME}}', '{{CONTACT_EMAIL}}'],
        }],
        total: 1,
      }),
    }))

    const results = await searchTemplates({ query: 'Datenschutzerklärung' })
    expect(results).toHaveLength(1)
    expect(results[0].documentTitle).toBe('Datenschutzerklärung (DSGVO-konform)')
    expect(results[0].templateType).toBe('privacy_policy')
    expect(results[0].placeholders).toContain('{{COMPANY_NAME}}')
    expect((results[0] as any).source).toBe('db')
  })

  it('fällt auf RAG zurück wenn Backend fehlschlägt', async () => {
    vi.stubGlobal('fetch', vi.fn()
      .mockRejectedValueOnce(new Error('Backend down'))
      .mockResolvedValueOnce({
        ok: true,
        json: () => Promise.resolve({
          results: [{
            regulation_name: 'DSGVO Art. 13',
            text: 'Informationspflichten',
            regulation_code: 'DSGVO-13',
            score: 0.8,
          }],
        }),
      })
    )

    const results = await searchTemplates({ query: 'test' })
    expect(results).toHaveLength(1)
    expect(results[0].documentTitle).toBe('DSGVO Art. 13')
    expect((results[0] as any).source).toBe('rag')
  })

  it('gibt [] zurück wenn beide Services down sind', async () => {
    vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('all down')))

    const results = await searchTemplates({ query: 'test' })
    expect(results).toEqual([])
  })
})
